Skip to content

Incorrect suggestion to define associated type in type parameter list #116464

Closed
@detly

Description

@detly

Code

pub trait One<T> {
    type Assoc;
}

impl<T, S> One<T, S> for () {}

Current output

error[E0107]: trait takes 1 generic argument but 2 generic arguments were supplied
 --> src/lib.rs:5:12
  |
5 | impl<T, S> One<T, S> for () {}
  |            ^^^ expected 1 generic argument
  |
note: trait defined here, with 1 generic parameter: `T`
 --> src/lib.rs:1:11
  |
1 | pub trait One<T> {
  |           ^^^ -
help: replace the generic bound with the associated type
  |
5 | impl<T, S> One<T, Assoc = S> for () {}
  |                   +++++++

For more information about this error, try `rustc --explain E0107`.

Desired output

error[E0107]: trait takes 1 generic argument but 2 generic arguments were supplied
 --> src/lib.rs:5:12
  |
5 | impl<T, S> One<T, S> for () {}
  |            ^^^ expected 1 generic argument
  |
note: trait defined here, with 1 generic parameter: `T`
 --> src/lib.rs:1:11
  |
1 | pub trait One<T> {
  |           ^^^ -
help: define the associated type in the implementation body
  |
5 | impl<T> One<T> for () {
  |     type Assoc = SomeType;
  |     ++++++++++++++++++++++
  | }

For more information about this error, try `rustc --explain E0107`.

Rationale and extra context

The suggestion is not valid syntax. Applying the original suggestion like so:

pub trait One<T> {
    type Assoc;
}

impl<T, S> One<T, Assoc = S> for () {}

...leads to this error instead:

 --> src/lib.rs:5:19
  |
5 | impl<T, S> One<T, Assoc = S> for () {}
  |                   ^^^^^^^^^ associated type not allowed here

For more information about this error, try `rustc --explain E0229`.

Note also that a more naive suggestion to keep the S parameter like so:

pub trait One<T> {
    type Assoc;
}

impl<T, S> One<T> for () {
    type Assoc = S;
}

...would fail because it's unconstrained:

error[E0207]: the type parameter `S` is not constrained by the impl trait, self type, or predicates
 --> src/lib.rs:5:9
  |
5 | impl<T, S> One<T> for () {
  |         ^ unconstrained type parameter

For more information about this error, try `rustc --explain E0207`.

Assoc needs to be a concrete type or an associated type of an input type parameter.

The diagnostic is identical in beta and nightly.

Metadata

Metadata

Assignees

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`D-invalid-suggestionDiagnostics: A structured suggestion resulting in incorrect code.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