-
Notifications
You must be signed in to change notification settings - Fork 13.6k
Closed
Labels
A-diagnosticsArea: Messages for errors, warnings, and lintsArea: Messages for errors, warnings, and lintsA-suggestion-diagnosticsArea: Suggestions generated by the compiler applied by `cargo fix`Area: Suggestions generated by the compiler applied by `cargo fix`D-newcomer-roadblockDiagnostics: Confusing error or lint; hard to understand for new users.Diagnostics: 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.Relevant to the compiler team, which will review and decide on the PR/issue.
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.
Metadata
Metadata
Assignees
Labels
A-diagnosticsArea: Messages for errors, warnings, and lintsArea: Messages for errors, warnings, and lintsA-suggestion-diagnosticsArea: Suggestions generated by the compiler applied by `cargo fix`Area: Suggestions generated by the compiler applied by `cargo fix`D-newcomer-roadblockDiagnostics: Confusing error or lint; hard to understand for new users.Diagnostics: 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.Relevant to the compiler team, which will review and decide on the PR/issue.