Skip to content

"does not live long enough" errors due to moving into match block should be more helpful #138741

Open
@TheNeikos

Description

@TheNeikos

Code

#[derive(Debug)]
struct Bar;

impl Bar {
    fn get_foo(&self) -> Foo<'_> {
        Foo {
            b: self
        }
    }
}

#[derive(Debug)]
struct Foo<'a> {
    b: &'a Bar
}

fn main() {
    let b = Bar;
    
    let f = match b {
        b => b.get_foo(),
    };
    
    println!("Hi: {f:?}");
}

Current output

Compiling playground v0.0.1 (/playground)
error[E0597]: `b` does not live long enough
  --> src/main.rs:22:14
   |
21 |     let f = match b {
   |         - borrow later stored here
22 |         b => b.get_foo(),
   |         -    ^         - `b` dropped here while still borrowed
   |         |    |
   |         |    borrowed value does not live long enough
   |         binding `b` declared here

For more information about this error, try `rustc --explain E0597`.
error: could not compile `playground` (bin "playground") due to 1 previous error

Desired output

It should mention that borrowing b would allow (or might allow?) the lifetime to be fine.

Rationale and extra context

The fact that match moves values is not super intuitive due to auto-refs. As using T or &T uses the same syntax. This does not make it always apparent what the value inside the different arms actually is. And even with inline hints, this could be easily missed due to the mental model being 'correct', despite not matching what the user wrote.

Other cases

Rust Version

rustc 1.85.0 (4d91de4e4 2025-02-17)
binary: rustc
commit-hash: 4d91de4e48198da2e33413efdcd9cd2cc0c46688
commit-date: 2025-02-17
host: x86_64-unknown-linux-gnu
release: 1.85.0
LLVM version: 19.1.7

Anything else?

Playground link: https://play.rust-lang.org/?version=stable&mode=debug&edition=2024&gist=3416b390fa1efe640fc7c2ddaa8b060d

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-diagnosticsArea: Messages for errors, warnings, and lintsT-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