⭐
World 10 Β· Super Flexible Code

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.”

The Big Idea A trait is a shared superpower that different types can have. It's like a contract: "If you have this trait, you promise you can do this special 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.

Think of it like this… A trait is like a badge that says "I can make a sound." A dog earns the badge by barking, a cat earns it by meowing. Same badge, different sounds! 🐢🐱

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. πŸŽ‰

Ferris says: Traits let very different types share the same skill. That means you can write code that works with anything that can speak β€” dogs, cats, even robots! πŸ€–
Try this! Add a new type called 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. ⭐

You learned… A trait is a shared superpower, like a contract. You use 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! ⏳