[E0521] `borrowed data escapes outside of method` difficult to understand with elided lifetimes
Nobody has claimed this yet.
- Dominant language
- Rust
- Stars
- 119k
- Forks
- 16.1k
- PR merge metrics
- PR metrics pending
Description
Code
trait T {}
impl T for () {}
struct S;
impl S {
fn make_t<'a>(&'a mut self) -> Box<dyn T + 'a> {
Box::new(())
}
}
fn foo(t: &mut Box<dyn T>) {
// irrelevant
}
fn bar(s: &mut S) {
let mut t = s.make_t();
foo(&mut t);
}
Current output
error[E0521]: borrowed data escapes outside of function
--> src/lib.rs:18:17
|
17 | fn bar(s: &mut S) {
| - - let's call the lifetime of this reference `'1`
| |
| `s` is a reference that is only valid in the function body
18 | let mut t = s.make_t();
| ^^^^^^^^^^
| |
| `s` escapes the function body here
| argument requires that `'1` must outlive `'static`
Desired output
error[E0521]: borrowed data escapes outside of function
--> src/lib.rs:18:17
|
17 | fn bar(s: &mut S) {
| - - let's call the lifetime of this reference `'1`
| |
| `s` is a reference that is only valid in the function body
19 | foo(&mut t);
| ^^^^^^
| |
| `t` has type `Box<dyn T + '1>`, but the function `foo`
| requires an argument of type `Box<dyn T + 'static>`.
Rationale and extra context
This is related to https://github.com/rust-lang/rust/issues/115783, but the issue would remain even if the error highlighted the correct location.
The readability issue arises from the fact that it isn't obvious where the 'static bound even comes from. I initially encountered this when interfacing with library code; while it was on me for not reading the type signature of the make_t closely enough to notice the 'a parameter, I think highlighting the fact that there's an elided + 'static bound in the Box<dyn T> type signature would make it much easier to track down the root cause.
Other cases
Rust Version
rustc 1.84.1 (e71f9a9a9 2025-01-27)
binary: rustc
commit-hash: e71f9a9a98b0faf423844bf0ba7438f29dc27d58
commit-date: 2025-01-27
host: x86_64-unknown-linux-gnu
release: 1.84.1
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 with the Rust reproducer and current E0521 output in the issue, then trace the compiler diagnostic path for this lifetime error. Compare it with the desired output, ensuring the elided 'static requirement is made explicit; done means the diagnostic explains that bound clearly for this case.
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