Skip to content

Improve borrow error when assigning borrowed local value to "argument by mutable reference" #99430

Open
@estebank

Description

@estebank

Given

fn f(mut p: &mut i32) {

    let mut number = 111;
    p = &mut number;

    *p = 2;
    println!("{}", *p);
}

we currently emit

error[E0597]: `number` does not live long enough
 --> f44.rs:4:9
  |
1 | fn f(mut p: &mut i32) {
  |             - let's call the lifetime of this reference `'1`
...
4 |     p = &mut number;
  |     ----^^^^^^^^^^^
  |     |   |
  |     |   borrowed value does not live long enough
  |     assignment requires that `number` is borrowed for `'1`
...
8 | }
  | - `number` dropped here while still borrowed

but it could be more informative:

error[E0597]: `number` does not live long enough
 --> f44.rs:4:9
  |
1 | fn f(mut p: &mut i32) {
  |             - let's call the lifetime of this reference `'1`
...
3 |     let mut number = 111;
  |             -----   --- this value is assigned to `number` and lives as long as `f`
  |             |
  |             this binding only lives for the duration of function `f` and gets dropped at the function
4 |     p = &mut number;
  |     ----^^^^^^^^^^^
  |     |   |
  |     |   borrowed value does not live long enough
  |     this assignment to `p` will outlive `f` because it is a `&mut i32` owned by the caller's scope
...
8 | }
  | - `number` dropped here while still borrowed

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-borrow-checkerArea: The borrow checkerA-diagnosticsArea: Messages for errors, warnings, and lintsA-lifetimesArea: Lifetimes / regionsD-newcomer-roadblockDiagnostics: Confusing error or lint; hard to understand for new users.D-papercutDiagnostics: An error or lint that needs small tweaks.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