Skip to content

Give a better error message for shared borrow treated as unique for purposes of lifetimes #76630

Open
@bonsairobo

Description

@bonsairobo

I tried this code:

#[derive(Default)]
struct Foo { i: i32, j: i32 }

impl Foo {
    fn modify_and_borrow(&mut self) -> &i32 { self.j += 1; &self.i }
}

fn main() {
    let mut foo = Foo::default();
    let mut refs = Vec::new();
    for _ in 0..2 {
        refs.push(foo.modify_and_borrow());
    }
}

I expected to see this happen:

The error should say something like, "cannot borrow foo as mutable while it is already borrowed as immutable."

Instead, this happened:

error[E0499]: cannot borrow `foo` as mutable more than once at a time
  --> src/main.rs:12:19
   |
12 |         refs.push(foo.modify_and_borrow());
   |                   ^^^ mutable borrow starts here in previous iteration of loop

Meta

Playground link:

https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=a6450c7200878a52ff8bf4466cb09f5f

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-diagnosticsArea: Messages for errors, warnings, and lintsA-lifetimesArea: Lifetimes / regionsC-bugCategory: This is a bug.D-confusingDiagnostics: Confusing error or lint that should be reworked.T-compilerRelevant to the compiler team, which will review and decide on the PR/issue.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions