Skip to content

Suggest how to workaround E0212 #69000

Closed
@nagisa

Description

@nagisa

It is not impossible for one to end up with a code that looks like this:

trait Banana<'a> { 
    type Assoc: Default;
}

struct Peach<X>(std::marker::PhantomData<X>);

impl<X: for<'a> Banana<'a>> Peach<X> {
    fn mango(&self) -> X::Assoc {
        Default::default()
    }
}

But fairly unintuitively the compiler rejects this code:

error[E0212]: cannot extract an associated type from a higher-ranked trait bound in this context
 --> src/lib.rs:8:24
  |
8 |     fn mango(&self) -> X::Assoc {
  |                        ^^^^^^^^

This can be made to work by specifying the lifetime for the associated type:

trait Banana<'a> { 
    type Assoc: Default;
}

struct Peach<X>(std::marker::PhantomData<X>);

impl<X: for<'a> Banana<'a>> Peach<X> {
    fn mango(&self) -> <X as Banana<'_>>::Assoc {
        Default::default()
    }
}

But it is fairly not obvious how to get there. We should suggest a similar transformation in the diagnostic.

cc @estebank

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-associated-itemsArea: Associated items (types, constants & functions)A-diagnosticsArea: Messages for errors, warnings, and lintsA-suggestion-diagnosticsArea: Suggestions generated by the compiler applied by `cargo fix`A-type-systemArea: Type systemC-enhancementCategory: An issue proposing an enhancement or a PR with one.D-terseDiagnostics: An error or lint that doesn't give enough information about the problem at hand.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