Trait does not have a constant size known at compile-time

Using the following code:

	trait A {
	fn do_it(&mut self);
}

struct B {

}

impl A for B {
	fn do_it(&mut self) {
		println!("B");
	}
}

struct C {

}

impl A for C {
	fn do_it(&mut self) {
		println!("C");
	}
}

pub fn main() {
	let mut test: Vec<A> = vec!(B {}, C {});

	for t in &mut test {
		t.do_it();
	}
}

I'm getting multiple errors saying: "A does not have a constant size known at compile-time"

2 Likes

I think you're looking for trait objects. The compiler doesn't know the size of the value just based on the trait, and at runtime you can put any value that implements A in the vector, it cannot know how to layout the vector. For more information read about the Sized special trait. You can accomplish what you want by putting the different objects into boxes.

I updated your code on the playground here to make it work.

Adding Box seems to have done the trick, thank you!

Strictly speaking, you don’t need a Box in this particular case - you can use borrowed trait objects: Playground

But if you want an owned trait object, then a Box is the way to go.

1 Like