rust-lang / rust-lang/rust

Borrow incorrectly "escapes" function when calling method of blanket impl for `'static` type

Open
#123,921 3 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

A-diagnostics C-bug D-incorrect T-compiler T-lang
Dominant language
Rust
Stars
119k
Forks
16.1k
PR merge metrics
PR metrics pending

Description

I tried this code (playground):

trait Trait {
    fn method(&self) {}
}

impl<T: 'static> Trait for T {} // requires 'static blanket impl

fn foo(t: &mut ()) { // requires &mut
    Trait::method(t); // works
    t.method(); // E0521 borrowed data escapes outside of function
}

I expected this to compile without error. Instead, I received E0521:

error[E0521]: borrowed data escapes outside of function
 --> src/lib.rs:9:5
  |
7 | fn foo(t: &mut ()) {
  |        -  - let's call the lifetime of this reference `'1`
  |        |
  |        `t` is a reference that is only valid in the function body
8 |     Trait::method(t); // works
9 |     t.method(); // E0521 borrowed data escapes outside of function
  |     ^^^^^^^^^^
  |     |
  |     `t` escapes the function body here
  |     argument requires that `'1` must outlive `'static`

For more information about this error, try `rustc --explain E0521`.
Meta

rustc --version --verbose:

rustc 1.79.0-nightly (0bf471f33 2024-04-13)
binary: rustc
commit-hash: 0bf471f339837af930ec90ef5e1e9cb232e99f29
commit-date: 2024-04-13
host: aarch64-unknown-linux-gnu
release: 1.79.0-nightly
LLVM version: 18.1.3

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

Start with the reproduction in src/lib.rs or the linked Rust Playground, and read the E0521 explanation with rustc --explain E0521. Compare the fully qualified Trait::method(t) call with t.method(); done means the method-call form no longer reports that the borrow must outlive 'static while preserving the shown blanket-impl behavior.

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.