Traits: Shared Superpowers
A dog can make a sound. A cat can make a sound. Theyβre totally different animals, but they share an ability: making a sound. In Rust, a shared ability like that is called a trait. β
A trait is like a promise. It says, βAnything with this trait can do this thing.β
Writing a trait
First we describe the superpower. Here we make a trait called Speak that says:
βanything that can speak gives back some words.β
trait Speak {
fn speak(&self) -> String;
}
Thatβs just the promise. It doesnβt say what the words are β each type fills that in itself.
Giving the superpower to types
The word impl means βthis type keeps the promise.β We teach a Dog and a Cat
how to speak, then call .speak() on each. Press βΆ Run!
Both the dog and the cat have the Speak superpower, but each one does it its own way. π
Cow and give it the Speak trait so it returns
"Moo!". Then print what the cow says. Press βΆ Run!
Quick quiz
What is a trait in Rust?
Exactly! A trait is a shared superpower. Any type that has it promises it can do that thing. β
impl to
give that power to a type, then call it with .speak(). Next up:
Lifetimes: How Long Things Live, where Rust makes sure borrowed things
don't disappear too soon! β³