Skip to content

borrow checker too restrictive in match statements, with confusing/confused compile errors #17462

Closed
@makoConstruct

Description

@makoConstruct
struct Node{  left:Option<Box<Node>>  }

fn leftmost_child(n:& mut Node)-> & mut Node {
    let mut leftest = n;
    loop {
        match leftest.left.as_mut() {
            Some(nl) => leftest = &mut **nl,
            None => break,
        }
    }
    leftest
}

fn main(){}

yeilds

<anon>:6:9: 6:21 note: previous borrow of `leftest.left` occurs here; the mutable borrow prevents subsequent moves, borrows, or modification of `leftest.left` until the borrow ends
<anon>:6        match leftest.left.as_mut() {
                      ^~~~~~~~~~~~
<anon>:12:2: 12:2 note: previous borrow ends here
<anon>:3 fn leftmost_child(n:& mut Node)-> & mut Node {
...
<anon>:12 }
          ^
<anon>:7:16: 7:35 error: cannot assign to `leftest` because it is borrowed
<anon>:7            Some(nl) => leftest = &mut **nl,
                                ^~~~~~~~~~~~~~~~~~~
<anon>:6:9: 6:21 note: borrow of `leftest` occurs here
<anon>:6        match leftest.left.as_mut() {
                      ^~~~~~~~~~~~
<anon>:11:2: 11:9 error: cannot borrow `*leftest` as mutable more than once at a time
<anon>:11   leftest
            ^~~~~~~
<anon>:6:9: 6:21 note: previous borrow of `leftest.left` occurs here; the mutable borrow prevents subsequent moves, borrows, or modification of `leftest.left` until the borrow ends
<anon>:6        match leftest.left.as_mut() {
                      ^~~~~~~~~~~~
<anon>:12:2: 12:2 note: previous borrow ends here
<anon>:3 fn leftmost_child(n:& mut Node)-> & mut Node {
...
<anon>:12 }
          ^

http://is.gd/7aqog5
Note that there's another error about being unable to assign to leftest within the match body. Should borrowing forbid reassignment here?

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-borrow-checkerArea: The borrow checkerC-bugCategory: This is a bug.T-compilerRelevant to the compiler team, which will review and decide on the PR/issue.fixed-by-NLLBugs fixed, but only when NLL is enabled.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions