Skip to content

Suggestion for E0308 produces invalid syntax for traits with unconstrained associated types, when a type parameter is expected #117501

Closed
@polina4096

Description

@polina4096

Code

trait MyTrait {
    type T;
    
    fn bar(self) -> Self::T;
}

fn foo<A: MyTrait, B>(a: A) -> B {
    return a.bar();
}

Current output

error[E0308]: mismatched types
 --> src/lib.rs:8:12
  |
7 | fn foo<A: MyTrait, B>(a: A) -> B {
  |                    -           - expected `B` because of return type
  |                    |
  |                    this type parameter
8 |     return a.bar();
  |            ^^^^^^^ expected type parameter `B`, found associated type
  |
  = note: expected type parameter `B`
            found associated type `<A as MyTrait>::T`
help: consider further restricting this bound
  |
7 | fn foo<A: MyTrait + <T = B>, B>(a: A) -> B {
  |                   +++++++++

Desired output

error[E0308]: mismatched types
 --> src/lib.rs:8:12
  |
7 | fn foo<A: MyTrait, B>(a: A) -> B {
  |                    -           - expected `B` because of return type
  |                    |
  |                    this type parameter
8 |     return a.bar();
  |            ^^^^^^^ expected type parameter `B`, found associated type
  |
  = note: expected type parameter `B`
            found associated type `<A as MyTrait>::T`
help: consider constraining the associated type `<A as MyTrait>::T` to `B`
  |
7 | fn foo<A: MyTrait<T = B>, B>(a: A) -> B {
  |                  +++++++

Rationale and extra context

When a type parameter is expected, but an unconstrained associated type is found rustc suggests a syntactically incorrect fix with a misleading help message about trait bounds instead of associated type constraints.

Other cases

trait MyTrait {
    type T;
}

fn foo<A: MyTrait, B>(val: A::T) -> B {
    val
}
trait MyTrait {
    type T;
}

fn foo<A: MyTrait, B>(val: A::T) {
    let _: B = val;
}
trait MyTrait {
    type T;
    fn bar(self) -> Self::T;
}

fn foo<A: MyTrait, B>(a: A) {
    let _: B = a.bar();
}

Anything else?

No response

Metadata

Metadata

Assignees

Labels

A-diagnosticsArea: Messages for errors, warnings, and lintsA-type-systemArea: Type systemD-incorrectDiagnostics: A diagnostic that is giving misleading or incorrect information.S-has-mcveStatus: A Minimal Complete and Verifiable Example has been found for this issueT-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