Skip to content

rustc should suggest trait bounds when attempting to use associated items on generic parameters. #101351

@BGR360

Description

@BGR360

Given the following code (playground):

trait Foo { type Associated; } struct Generic<T> { field: T::Associated, }

The current output is:

error[E0220]: associated type `Associated` not found for `T` --> src/lib.rs:6:15 | 6 | field: T::Associated, | ^^^^^^^^^^ associated type `Associated` not found 

Ideally the output should look like:

error[E0220]: associated type `Associated` not found for `T` --> src/lib.rs:6:15 | 6 | field: T::Associated, | ^^^^^^^^^^ associated type `Associated` not found | help: items from traits can only be used if the type parameter is bounded by the trait help: the following trait defines an item `Associated`, perhaps you need to restrict type parameter `T` with it: | 5 | struct Generic<T: Foo> { | +++++ 

It already does this for trait methods (playground):

pub trait Foo { fn do_it(&self); } fn use_it<T>(input: T) { input.do_it(); } fn main() { use_it(42); }
error[E0599]: no method named `do_it` found for type parameter `T` in the current scope --> src/main.rs:6:11 | 6 | input.do_it(); | ^^^^^ method not found in `T` | = help: items from traits can only be used if the type parameter is bounded by the trait help: the following trait defines an item `do_it`, perhaps you need to restrict type parameter `T` with it: | 5 | fn use_it<T: Foo>(input: T) { | +++++ 

And it does it (sorta, the message is more terse) if you qualify with as Trait (playground):

trait Foo { type Associated; } struct Generic<T> { field: <T as Foo>::Associated, }
error[E0277]: the trait bound `T: Foo` is not satisfied --> src/lib.rs:6:12 | 6 | field: <T as Foo>::Associated, | ^^^^^^^^^^^^^^^^^^^^^^ the trait `Foo` is not implemented for `T` | help: consider restricting type parameter `T` | 5 | struct Generic<T: Foo> { | +++++ 

@rustbot label +D-newcomer-roadblock +D-terse +A-associated-items

Metadata

Metadata

Assignees

Labels

A-associated-itemsArea: Associated items (types, constants & functions)A-diagnosticsArea: Messages for errors, warnings, and lintsD-newcomer-roadblockDiagnostics: Confusing error or lint; hard to understand for new users.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