This trait cannot be...
If one has ever run into this #Rust error, it is probably the case that adding traits just dead-ended. There is even a complete section in the Rust docs dedicated to the title topic. And a longer list of articles and posts that miss the point.
Also, it is probably the case that traits could be placed somewhere more useful.
Size is important in Rust. It allows the language to do wonders with it. But it is also true that Rust can be cranky: what worked in one place may fail to compile somewhere else.
impl Struct1{
pub fn new() ->Self{
let mut t2_v: Vec<Box<dyn Trait2>> = vec![];
The previous snippet can cause the problem pictured at the top. Traits by definition need an implementor to obtain a size. So this snippet is a can of worms: there are several other causes of the "this trait cannot...".
Traits can be the best companion for generics. The following:
trait Trait2: Sized ... {
fn trait2_function(&self) -> bool;
fn new() -> Self;
}
struct Struct1<T: Trait2> {
field1: i32,
trait2_vec: Vec<T>,
The compiler will enforce the trait contract and the size requirement. It will replace T with an struct during compilation so there is no performance penalty. The condition that raises the myriad of trait errors is gone.