Skip to content

On E0308, detect incorrect attempts to use trait objects #102629

Closed
@estebank

Description

https://users.rust-lang.org/t/expected-trait-object-dyn-trait-found-struct-struct/82198

When encountering cases where the user's intent is to have a trait object, but we produce an E0308, we should put some effort in sending them in the right direction. We should provide a suggestion with the right code to properly box and erase the type in the appropriate branches.

let a: dyn Trait = if true {
    Struct
} else {
    foo() // -> dyn Trait
};
let a: dyn Trait = if true {
    Struct
} else {
    foo() // -> Box<dyn Trait>
};
let a: dyn Trait = if true {
    Struct
} else {
    foo() // -> impl Trait
};
let a: Box<dyn Trait> = if true {
    Box::new(Struct)
} else {
    foo() // -> dyn Trait
};
let a: Box<dyn Trait> = if true {
    Box::new(Struct)
} else {
    foo() // -> Box<dyn Trait>
};
let a: Box<dyn Trait> = if true {
    Box::new(Struct)
} else {
    foo() // -> impl Trait
};
let a: Trait = if true {
    Struct
} else {
    foo() // -> dyn Trait
};
let a: Trait = if true {
    Struct
} else {
    foo() // -> Box<dyn Trait>
};
let a: Trait = if true {
    Struct
} else {
    foo() // -> impl Trait
};
let a: Box<dyn Trait> = if true {
    Struct
} else {
    foo() // -> Box<dyn Trait>
};
let a: dyn Trait = if true {
    Struct
} else {
    foo() // -> impl Trait
};

We also want to do this if the binding doesn't have an explicit type, but that will require looking at the diverging code branches to see if any of them is a "root" trait (if there are multiple trait objects of different traits, and any of them is super trait to all others), and for the explicit types if they implement the trait and can be coerced to the desired trait object.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

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`D-newcomer-roadblockDiagnostics: Confusing error or lint; hard to understand for new users.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