This trait cannot be...

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.

To view or add a comment, sign in

More articles by Jose Cornado

  • #Rust, C, And FFI

    Combining rust and C is easy. And if we use the "green programming languages" paper as cloud proxy costs, it is…

  • Asynchronous rust, a tad easier

    Recently, I started to port a project written in Java to #Rust. It seems to have performance benefits without the…

  • Economics Killed Agile

    In 2001, I was putting the finishing touches on an autonomous, QA automation server/CI environment for a multi-model…

Insights from the community

Others also viewed

Explore topics