Skip to content

E0308 mismatched type on trait impl with different concrete types #155366

@DanielEScherzer

Description

@DanielEScherzer

Code

trait Value {}

struct First {}
impl Value for First {}

struct Second {}
impl Value for Second {}

fn get_value(first: bool) -> impl Value {
    if first {
        return First {};
    }
    Second {}
}

Current output

Compiling playground v0.0.1 (/playground)
error[E0308]: mismatched types
  --> src/lib.rs:13:5
   |
 9 | fn get_value(first: bool) -> impl Value {
   |                              ---------- expected `First` because of return type
...
13 |     Second {}
   |     ^^^^^^^^^ expected `First`, found `Second`

For more information about this error, try `rustc --explain E0308`.
error: could not compile `playground` (lib) due to 1 previous error

Desired output

Compiling playground v0.0.1 (/playground)
error[E0308]: mismatched types
  --> src/lib.rs:13:5
   |
 9 | fn get_value(first: bool) -> impl Value {
   |                              ---------- expected a single type implementing `Value` because of return type
...
   |
11 |         return First {};
   |                ^^^^^ return type resolved to be `First`
...
13 |     Second {}
   |     ^^^^^^^^^ expected `First`, found `Second`

For more information about this error, try `rustc --explain E0308`.
error: could not compile `playground` (lib) due to 1 previous error

Rationale and extra context

Even though I had read the entire reference, I forgot about the rule that

Each possible return value from the function must resolve to the same concrete type.

And the existing message suggests that the return type in the signature is what breaks the Second {} return, but it isn't - instead, it is the fact that First {} is returned above

Other cases

Rust Version

1.94.1

Anything else?

No response

Metadata

Metadata

Assignees

Labels

A-diagnosticsArea: Messages for errors, warnings, and lintsD-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
No fields configured for issues without a type.

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions