rust-lang / rust-lang/rust

`dyn for<'a>` lifetime inference does not work within typedefs, but works elsewhere

Open
#153,938 3 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

A-lifetimes C-bug needs-triage
Dominant language
Rust
Stars
119k
Forks
16.2k
PR merge metrics
PR metrics pending

Description

I tried this code:

pub trait Foo<'a> { type Ty: 'a; }

pub fn i_work<'x>(x: &'x [u8]) {
  // can take an outside lifetime parameter just fine
  let _: <dyn for<'a> Foo<'a, Ty = &'x [u8]> as Foo<'_>>::Ty = x;
  // can be infered
  let _: <dyn for<'a> Foo<'a, Ty = &[u8]> as Foo<'_>>::Ty = x;
  // can be explicit
  let _: <dyn for<'a> Foo<'a, Ty = &'a [u8]> as Foo<'_>>::Ty = x;
  // infers a lifetime just fine (which is probably 'static)
  let _: <dyn for<'a> Foo<'a, Ty = &[u8]> as Foo<'_>>::Ty = &[1, 2, 3];
}

// Fails:
// type IDontWork = Vec<<dyn for<'a> Foo<'a, Ty = &[u8]> as Foo<'static>>::Ty>;
pub type IWork = Vec<<dyn for<'a> Foo<'a, Ty = &'a [u8]> as Foo<'static>>::Ty>;

I expected to see this happen: Code compiles successfully because the lifetime parameter for &[u8] should be inferred as there is only one lifetime in scope, and that lifetime comes from a binder rather than the typedef.

Instead, this happened: Code does not compile. rustc complains about needing an explicit lifetime parameter.

Meta

rustc --version --verbose: 1.94.0 stable (tested in playground)

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 compiling the minimal reproducer in the issue, comparing the working expression forms with the failing typedef IDontWork and the explicit-lifetime IWork alias. Trace the compiler's lifetime inference for associated types under the dyn for<'a> binder. Done means the typedef form accepts the inferred lifetime and a regression test covers both the failing and working cases.

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
Active
Clarity
Mostly clear
Newbie friendliness
45/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.