rust-lang / rust-lang/rust

Confusing lifetime error when using HRTB and closure

Open
#143,588 1 comment 1 reaction 0 assignees View on GitHub

Nobody has claimed this yet.

A-higher-ranked A-implied-bounds C-bug T-types
Dominant language
Rust
Stars
119k
Forks
16.1k
PR merge metrics
PR metrics pending

Description

I tried this code:

trait StorageIterator {
    type KeyType<'a> where Self: 'a;
}

fn f<I: for<'a> StorageIterator<KeyType<'a> = &'a [u8]>>() {
    || true;
}

I expected to see this happen: This code can pass compilation.

Instead, this happened: Rustc reports a lifetime error.

error: `I` does not live long enough
 --> <source>:6:5
  |
6 |     || true;
  |     ^^^^^^^

error: aborting due to 1 previous error

Following situations can pass compilation:

  1. remove closure
trait StorageIterator {
    type KeyType<'a> where Self: 'a;
}

fn f<I: for<'a> StorageIterator<KeyType<'a> = &'a [u8]>>() {}
  1. remove where bound in trait
trait StorageIterator {
    type KeyType<'a>;
}

fn f<I: for<'a> StorageIterator<KeyType<'a> = &'a [u8]>>() {
    || true;
}
  1. add 'static for generic I
trait StorageIterator {
    type KeyType<'a> where Self: 'a;
}

fn f<I: for<'a> StorageIterator<KeyType<'a> = &'a [u8]> + 'static>() {
    || true;
}
Meta

rustc --version --verbose:

rustc 1.88.0 (6b00bc388 2025-06-23)
binary: rustc
commit-hash: 6b00bc3880198600130e1cf62b8f8a93494488cc
commit-date: 2025-06-23
host: x86_64-unknown-linux-gnu
release: 1.88.0
LLVM version: 20.1.5

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 by reproducing the minimal example with rustc 1.88.0 and compare it with the three compiling variants in the issue. Investigate how HRTBs, generic associated types, the where Self: 'a bound, and closure creation interact. Done means the example compiles as expected or the diagnostic accurately explains the required lifetime constraint, with regression coverage added in the relevant compiler tests.

Written by the indexing model from the issue text.

Assessment

Tech stack
rust
Domain
compilers
Issue type
Bug
Difficulty
5/5
Estimated time
Over a week
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
32/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.