On E0308, detect incorrect attempts to use trait objects #102629
Closed
Description
opened on Oct 3, 2022
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