liveBook · Manning

Sized trait

As explained in Idiomatic Rust

The Rust Sized trait marks types whose size is known at compile time.

Sized marks types whose size is known at compile time. Generic type parameters require Sized by default; `T: ?Sized` makes that bound optional. Trait objects are unsized, so they cannot be stored directly or in a `Vec`. Smart pointers such as `Box` can hold them: construct a box from a concrete type, then coerce it to `Box<dyn Trait>`. section 2.2.6 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

A vector can store boxes of different concrete types through a shared trait object; calls are limited to methods on that trait. section 2.2.6

How Idiomatic Rust covers it

How deep it goes
Explains compile-time sizing, default generic bounds, ?Sized smart-pointer support, and why Vec cannot contain unsized values directly.
Examples
Demonstrates a heterogeneous Vec<Box<dyn MyTrait>> holding two concrete types and calling their shared trait method.
What you can do after
Apply it via ?Sized bounds and Box<dyn Trait> when storing trait objects.
How it connects
Connects Sized to trait objects, generic bounds, Box, and Vec.

Related concepts

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.