Confusing error message when closures return references based on their arguments
Nobody has claimed this yet.
- Dominant language
- Rust
- Stars
- 119k
- Forks
- 16.1k
- PR merge metrics
- PR metrics pending
Description
Code
struct Val {
inner: u32
}
fn main() {
let get_str = |val: &Val| &val.inner;
println!("{}", get_str(&Val { inner: 1 }));
}
Current output
error: lifetime may not live long enough
--> src/main.rs:6:31
|
6 | let get_str = |val: &Val| &val.inner;
| - - ^^^^^^^^^^ returning this value requires that `'1` must outlive `'2`
| | |
| | return type of closure is &'2 u32
| let's call the lifetime of this reference `'1`
Desired output
Rationale and extra context
I'm not sure what this specific limitation would be called, but I ran into it recently and thought that the error could give some advice on how to solve it. I'm not sure what the best way to do that is, so I haven't filled out the desired output section.
I was a bit surprised to learn that
struct Val {
inner: u32
}
fn main() {
let get_str = |val: &Val| -> &u32 { &val.inner };
println!("{}", get_str(&Val { inner: 1 }));
}
still has the same error (namely, &Val and &u32 are assigned two separate lifetimes), whereas
struct Val {
inner: u32
}
fn main() {
let get_str: fn(&Val) -> &u32 = |val: &Val| &val.inner;
println!("{}", get_str(&Val { inner: 1 }));
}
fixes the issue. I'm guessing there's some subtle differences in the way a type is created for a closure (even when the return type explicitly written out) versus specifying the type manually, but I'm honestly not sure. If there's some documentation regarding this, it might be a good idea to mention that in the error message.
Other cases
Rust Version
rustc 1.84.0 (9fc6b4312 2025-01-07)
binary: rustc
commit-hash: 9fc6b43126469e3858e2fe86cafb4f0fd5068869
commit-date: 2025-01-07
host: x86_64-unknown-linux-gnu
release: 1.84.0
LLVM version: 19.1.5
Anything else?
No response
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Start by reproducing the closure example with rustc 1.84.0, then compare its diagnostic with the explicitly typed function-pointer version described in the issue. Investigate the closure lifetime error diagnostic; done should provide clear, actionable guidance or relevant documentation for this limitation.
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
- Needs clarification
- Newbie friendliness
- 30/100