Skip to content

Confusing lifetime error when using HRTB and closure #143588

Open
@silver-ymz

Description

@silver-ymz

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-higher-rankedArea: Higher-ranked things (e.g., lifetimes, types, trait bounds aka HRTBs)A-implied-boundsArea: Implied bounds / inferred outlives-boundsC-bugCategory: This is a bug.T-typesRelevant to the types team, which will review and decide on the PR/issue.needs-triageThis issue may need triage. Remove it if it has been sufficiently triaged.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions