Skip to content

Borrow checker doesn't accept certain valid case when branch involves #57165

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
upsuper opened this issue Dec 28, 2018 · 1 comment
Open

Borrow checker doesn't accept certain valid case when branch involves #57165

upsuper opened this issue Dec 28, 2018 · 1 comment
Labels
A-NLL Area: Non-lexical lifetimes (NLL) NLL-polonius Issues related for using Polonius in the borrow checker T-compiler Relevant to the compiler team, which will review and decide on the PR/issue.

Comments

@upsuper
Copy link
Contributor

upsuper commented Dec 28, 2018

The compiler currently rejects the following code:

struct X {
    next: Option<Box<X>>,
}

fn main() {
    let mut b = Some(Box::new(X { next: None }));
    let mut p = &mut b;
    while let Some(now) = p {
        if true {
            p = &mut now.next;
        }
    }
}

It complains that now double mutably borrows p.0.

This explanation is not very convincing. If you rewrite it this way:

    while let Some(now) = p {
        p = &mut now.next;
    }

the compile would happily accept it, and compiler certainly also accepts

    while let Some(now) = p {
        // empty body
    }

so basically whatever the condition of if evaluates to, the original code should always be valid in terms of borrowing.

I'm not sure if I'm missing something, but it seems to me this is a bug of the borrow checker?

@upsuper
Copy link
Contributor Author

upsuper commented Dec 28, 2018

FWIW, if the code inside if is changed to

p = &mut p.as_mut().unwrap().next;

then it compiles. But I see no reason why the original code should be rejected.

cc @iovxw

@matthewjasper matthewjasper added A-NLL Area: Non-lexical lifetimes (NLL) NLL-polonius Issues related for using Polonius in the borrow checker labels Dec 28, 2018
@crlf0710 crlf0710 added the T-compiler Relevant to the compiler team, which will review and decide on the PR/issue. label Jun 11, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
A-NLL Area: Non-lexical lifetimes (NLL) NLL-polonius Issues related for using Polonius in the borrow checker T-compiler Relevant to the compiler team, which will review and decide on the PR/issue.
Projects
None yet
Development

No branches or pull requests

3 participants