Skip to content

Detect when if/else is tail expression has mismatched types that could be a boxed trait #69107

Closed
@estebank

Description

@estebank

Given the following

struct S;
struct Y;

trait Trait {}

impl Trait for S {}
impl Trait for Y {}

fn baz() -> impl Trait {
    if true {
        S
    } else {
        Y
    }
}

we currently emit

error[E0308]: `if` and `else` have incompatible types
  --> src/main.rs:13:9
   |
10 | /     if true {
11 | |         S
   | |         - expected because of this
12 | |     } else {
13 | |         Y
   | |         ^ expected struct `S`, found struct `Y`
14 | |     }
   | |_____- `if` and `else` have incompatible types

We should suggest changing the return type from impl Trait to Box<dyn Trait> and boxing the two branches. I think this is the last missing suggestion we can give involding impl Trait and dyn Trait returns.

Follow up to #68110.

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-diagnosticsArea: Messages for errors, warnings, and lintsA-suggestion-diagnosticsArea: Suggestions generated by the compiler applied by `cargo fix`C-enhancementCategory: An issue proposing an enhancement or a PR with one.D-papercutDiagnostics: An error or lint that needs small tweaks.P-lowLow priorityT-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