liveBook · Manning

Unsized type

As explained in Idiomatic Rust

An unsized type is a Rust type whose size is not known at compile time for direct storage.

An unsized type has no compile-time-known size for direct storage. Trait objects such as `dyn MyTrait` are unsized, so they cannot be stored directly in a `Vec`. A smart pointer such as `Box` can hold one: the concrete type is known when the box is created, then coerced to the trait-object type. section 2.2.6

let mut v = Vec::<Box<dyn MyTrait>>::new();

v.push(Box::new(MyStruct1 {}));          #1
v.push(Box::new(MyStruct2 {}));            #2

v.iter().for_each(|i| i.trait_hello());                   #3
// v.iter().for_each(|i| i.struct_hello()); error!    #4

See a `Vec` containing boxed trait objects for two concrete types; each can call the trait method, but not a concrete-type-only method. section 2.2.6

How Idiomatic Rust covers it

How deep it goes
Defines unsized trait objects and explains their storage constraints, including why `Vec` requires indirection.
Examples
Demonstrates storing two concrete types in `Vec<Box<dyn MyTrait>>` and calling their shared trait method.
What you can do after
Understand why trait objects need indirection for storage and how `Box` enables their use in a vector.
How it connects
Connects trait objects with `Sized`, `Box`, `Vec`, and smart pointers.

This explainer was generated by Manning's knowledge graph from the text of Idiomatic Rust. The section links point to the parts of the book it draws on.