Skip to content

The type-checker assumes that Trait<'a>::AssociatedType may be outlived by 'a, even with "where AssociatedType: 'a" #63253

Open
@hiddenhare

Description

@hiddenhare
trait Trait<'a> {
    type Ty;
    fn method(ty_ref: &'a Self::Ty) where Self::Ty: 'a { }
}

fn caller<'a, T: Trait<'a>>(arg: &'a T::Ty) where T::Ty: 'a {
    T::method(arg)
}

Compilation fails on the playground (for stable 1.36.0 and nightly 1.38.0) with this error:

Compiling playground v0.0.1 (/playground)
error[E0309]: the associated type `<T as Trait<'_>>::Ty` may not live long enough
 --> src/lib.rs:7:9
  |
7 |         T::method(arg)
  |         ^^^^^^^^^
  |
  = help: consider adding an explicit lifetime bound `<T as Trait<'_>>::Ty: 'a`...
note: ...so that the type `<T as Trait<'_>>::Ty` will meet its required lifetime bounds
 --> src/lib.rs:7:9
  |
7 |         T::method(arg)
  |         ^^^^^^^^^

error: aborting due to previous error

Compilation succeeds if I make any of the following changes:

  • Add a lifetime constraint to Ty at its definition site, type Ty: 'a;

  • Move the lifetime parameter from the trait to the method, fn method<'a>(...)

Compilation fails with the same error message if I change method into a free function:

trait Trait<'a> {
    type Ty;
}

fn method<'a, T: Trait<'a>>(_arg: &'a T::Ty) where T::Ty: 'a { }

fn caller<'a, T: Trait<'a>>(arg: &'a T::Ty) where T::Ty: 'a {
    method::<T>(arg)
}

Even if this is intended behaviour, the error message could be improved.

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-associated-itemsArea: Associated items (types, constants & functions)A-diagnosticsArea: Messages for errors, warnings, and lintsA-lifetimesArea: Lifetimes / regionsC-enhancementCategory: An issue proposing an enhancement or a PR with one.T-compilerRelevant to the compiler team, which will review and decide on the PR/issue.T-langRelevant to the language team, which will review and decide on the PR/issue.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions