trait-concept
Rust Owned heterogeneous trait-object collections
A vector needs one element type. Boxing different implementations behind the same trait-object interface gives all elements a common sized handle while retaining ownership. Use this when the set of implementation types is open; an enum may suit a fixed set. Expected output (not executed): saved synced Why: Box owns each value; the vector owns each Box. Non-zero-sized boxed payloads ordinarily use heap storage; zero-sized values need no allocation. Common mistake: Trying to build Vec<dyn Job> directly, although the element type is unsized.
Formal Syntax & Structure
rust syntaxrust
Vec<Box<dyn Trait>>Working Example
Example Snippetrust
trait Job { fn run(&self) -> &str; }struct Save;struct Sync;impl Job for Save { fn run(&self) -> &str { "saved" } }impl Job for Sync { fn run(&self) -> &str { "synced" } }fn main() { let jobs: Vec<Box<dyn Job>> = vec![Box::new(Save), Box::new(Sync)]; for job in &jobs { println!("{}", job.run()); }}