Skip to content
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

Strange borrowing scope #96702

Closed
Rexagon opened this issue May 4, 2022 · 2 comments
Closed

Strange borrowing scope #96702

Rexagon opened this issue May 4, 2022 · 2 comments
Labels
C-bug Category: This is a bug.

Comments

@Rexagon
Copy link

Rexagon commented May 4, 2022

I tried this code:

pub struct Test {
    pub data: Option<u32>,
    pub other_data: u32,
}

impl Test {
    pub fn preload(&mut self) -> &u32 {
        if let Some(data) = &self.data {
            return data;
        }

        // Why `self.data` is still borrowed here?
        // Manually adding scope around `if {}` doesn't help.
        self.data = Some(123);

        &self.other_data
    }
}

I expected to see this happen: it compiles

Instead, this happened:

error[E0506]: cannot assign to `self.data` because it is borrowed
  --> <source>:12:9
   |
7  |     pub fn preload(&mut self) -> &u32 {
   |                    - let's call the lifetime of this reference `'1`
8  |         if let Some(data) = &self.data {
   |                             ---------- borrow of `self.data` occurs here
9  |             return data
   |                    ---- returning this value requires that `self.data` is borrowed for `'1`
...
12 |         self.data = Some(123);
   |         ^^^^^^^^^^^^^^^^^^^^^ assignment to borrowed `self.data` occurs here

error: aborting due to previous error

For more information about this error, try `rustc --explain E0506`.
Compiler returned: 1

Meta

rustc --version --verbose:

rustc 1.60.0 (7737e0b5c 2022-04-04)
binary: rustc
commit-hash: 7737e0b5c4103216d6fd8cf941b7ab9bdbaace7c
commit-date: 2022-04-04
host: x86_64-unknown-linux-gnu
release: 1.60.0
LLVM version: 14.0.0
@Rexagon Rexagon added the C-bug Category: This is a bug. label May 4, 2022
@Urgau
Copy link
Member

Urgau commented May 4, 2022

It's a limitation of the current borrow checker, using the unstable compiler option -Zpolonius makes the code compiles.

https://rust.godbolt.org/z/PKoaxP3G4

@ehuss
Copy link
Contributor

ehuss commented May 4, 2022

Thanks for the report! As mentioned, this is a known limitation of the borrow checker. Closing as a duplicate of #54663 (or one of the other issues linked there).

@ehuss ehuss closed this as completed May 4, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
C-bug Category: This is a bug.
Projects
None yet
Development

No branches or pull requests

3 participants