Many Shapes, One Box
Imagine a list of different animals β a dog, a cat, a duck. They are all different, but they can all make a sound. πΎ Today weβll learn how Rust lets us keep different types together in one list and ask each of them to do the same thing.
A trait is a shared promise
Way back in World 10 we met traits. A trait is a list of things a type promises
it can do. Here we make a trait called Speak β anything that has Speak promises
it can make a sound.
trait Speak {
fn speak(&self) -> String;
}
A Dog and a Cat are totally different types. But if they both promise Speak,
we can treat them the same way when we just want them to talk. π£οΈ
Putting them in one box
Normally a Vec (a list) can only hold one type. So how do we mix dogs and cats?
We wrap each one in a Box<dyn Speak>. The word dyn means βany type that keeps
the Speak promise.β Now the list doesnβt care what animal it is β only that it
can speak!
Box<dyn Speak> means "a box holding some type that promises
Speak β we don't need to know exactly which one."