rust-lang / rust-lang/rust

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

Open
#138,741 0 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

A-diagnostics T-compiler
Dominant language
Rust
Stars
119k
Forks
16.1k
PR merge metrics
PR metrics pending

Description

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

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Reproduce the example with rustc 1.85.0 or the linked Rust Playground and inspect the E0597 diagnostic produced for the match arm. The change is done when this case explains that borrowing b could make the lifetime valid, with the diagnostic remaining correct for related cases.

Written by the indexing model from the issue text.

Assessment

Tech stack
rust
Domain
compilers
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.