Skip to content

no associated item found for struct in the current scope while it exists #71054

Open
@Lonami

Description

@Lonami

The following code (playground):

trait Trait {
    type Associated;

    fn instance() -> Self::Associated;
}

struct Associated;
struct Struct;

impl Trait for Struct {
    type Associated = Associated;

    fn instance() -> Self::Associated {
        Self::Associated
    }
}

Fails with this error:

error[E0599]: no associated item named `Associated` found for struct `Struct` in the current scope
  --> src/lib.rs:14:15
   |
8  | struct Struct;
   | -------------- associated item `Associated` not found for this
...
14 |         Self::Associated
   |               ^^^^^^^^^^ associated item not found in `Struct`

However, if we alter instance() slightly to either of these, the code compiles successfully:

    fn instance() -> Self::Associated {
        Self::Associated {} // {} even though we have `struct S;`, not `struct S {}`
    }
    fn instance() -> Self::Associated {
        Associated // outer scope struct definition
    }

It is worth mentioning that explicitly using as Trait does not solve the issue, and fails with a different error:

    fn instance() -> Self::Associated {
        <Self as Trait>::Associated
    }

Error:

error[E0575]: expected method or associated constant, found associated type `Trait::Associated`
  --> src/lib.rs:14:9
   |
14 |         <Self as Trait>::Associated
   |         ^^^^^^^^^^^^^^^^^^^^^^^^^^^
   |
   = note: can't use a type alias as a constructor

Adding {}:

    fn instance() -> Self::Associated {
        <Self as Trait>::Associated {}
    }

Fails with:

error: expected one of `.`, `::`, `;`, `?`, `}`, or an operator, found `{`
  --> src/lib.rs:14:37
   |
14 |         <Self as Trait>::Associated {}
   |                                     ^ expected one of `.`, `::`, `;`, `?`, `}`, or an operator

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-associated-itemsArea: Associated items (types, constants & functions)C-bugCategory: This is a bug.T-compilerRelevant to the compiler team, which will review and decide on the PR/issue.T-langRelevant to the language team

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions