Skip to content

Misleading type error when generic parameter is sole mismatch. #76086

Closed
@iximeow

Description

@iximeow

Some Rust (playground):

struct Generic<T> {
    inner: T,
}

impl<T> Generic<T> {
    fn foo() -> Generic<()> {
        Self { inner: () }
    }
}

yields an error about the mismatched type of inner:

error[E0308]: mismatched types
 --> src/lib.rs:7:23
  |
5 | impl<T> Generic<T> {
  |      - this type parameter
6 |     fn foo() -> Generic<()> {
7 |         Self { inner: () }
  |                       ^^ expected type parameter `T`, found `()`
  |
  = note: expected type parameter `T`
                  found unit type `()`

but I know it should be () - the return type on foo also expects T to be ()! The second error is somewhat more helpful:

error[E0308]: mismatched types
 --> src/lib.rs:7:9
  |
5 | impl<T> Generic<T> {
  |      - this type parameter
6 |     fn foo() -> Generic<()> {
  |                 ----------- expected `Generic<()>` because of return type
7 |         Self { inner: () }
  |         ^^^^^^^^^^^^^^^^^^ expected `()`, found type parameter `T`
  |
  = note: expected struct `Generic<()>`
             found struct `Generic<T>`

The actual issue I'd had writing this was Self { inner: () } instead of Generic { inner: () }. It would have been helpful if rustc could have concluded that the type I'd wanted matched the function's return type, and that the issue was Self being Generic<T> and causing the mismatch.

cc @estebank who'd asked me to write up an issue with a reproduction.

Apologies for the mushy title, I couldn't think of something more precise - very open to rewording if someone's got a better one-liner.

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-diagnosticsArea: Messages for errors, warnings, and lintsC-enhancementCategory: An issue proposing an enhancement or a PR with one.D-confusingDiagnostics: Confusing error or lint that should be reworked.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