I have this code (playground):
trait NodeLike: Sized {}
fn main() {
let s: Box<NodeLike> = panic!();
}
Which does not compile:
error[E0038]: the trait `NodeLike` cannot be made into an object
--> src/main.rs:4:12
|
4 | let s: Box<NodeLike> = panic!();
| ^^^^^^^^^^^^^ the trait `NodeLike` cannot be made into an object
|
= note: the trait cannot require that `Self : Sized`
After all I read, I still don't understand why it does not compile and why it does without the Sized
constraint.
As far as I know:
Box<NodeLike>
is treated asBox<dyn NodeLike>
which uses dynamic dispatch for method calls.Box<NodeLike>
is sized anyways, regardless of its item type.- The sized/unsized theory is necessary because there are types whose size is not known upfront (like arrays or strings).
- The
Sized
marker on traits enforces implementing types to be sized.
What does requiring that implementing types are Sized
have to do with not being able to have objects (with dynamic dispatch) of that trait?