Skip to content

rustc thinks a lifetime bound is necessary when passing an associated type into a nested call #101601

Closed
@BGR360

Description

@BGR360

No idea how to more effectively describe this problem in the title. Open to suggestions.

The following code fails to compile on stable (1.63.0) and nightly (playground):

trait Trait {
    type Associated;
}

struct Type<'a, T> {
    field: &'a T,
}

impl<'a, T> Type<'a, T>
where
    T: Trait,
{
    fn foo(param: T::Associated) {
        Self::bar(param);
    }

    fn bar(_: T::Associated) {}
}
error[E0309]: the parameter type `T` may not live long enough
  --> src/lib.rs:15:9
   |
15 |         Self::bar(param);
   |         ^^^^^^^^^ ...so that the type `T` will meet its required lifetime bounds
   |
help: consider adding an explicit lifetime bound...
   |
11 |     T: Trait + 'a,
   |              ++++

Removing the call to Self::bar makes the code compile just fine. It only fails when you try to call bar from inside foo.

This is really baffling to me. How is 'a even involved here?

Hint 1: It compiles if Type instead owns the T (playground):

struct Type<'a, T> {
    field: T,
    extra: &'a str
}

Hint 2: It compiles if foo and bar are methods instead of associated functions (playground).

Hint 3: It compiles if you do Type::<'_, T>::bar instead of Self::bar (playground).

I suppose it's possible that this isn't a bug, but if that's the case, then it's a corner of the language I have never hit before, and the diagnostics need a lot of work.

@rustbot label +A-associated-items +A-traits +A-lifetimes

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-associated-itemsArea: Associated items (types, constants & functions)A-lifetimesArea: Lifetimes / regionsA-trait-systemArea: Trait systemC-bugCategory: This is a bug.T-compilerRelevant to the compiler 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