Shared Behavior
What if different types need to do the same kind of thing? For example, both a Dog and a Cat can "speak", but they make different sounds. In Rust, you define this shared behavior with traits.
Defining a Trait
A trait is like a promise: "Any type that implements this trait must provide these methods."
This says: any type with the Greet trait must have a hello method that returns a String.
Implementing a Trait
The impl Greet for Robot block provides Robot's version of the hello method.
Multiple Types, One Trait
Different types can implement the same trait differently:
Default Methods
Traits can provide a default implementation that types can use or override:
Trait Parameters
You can write functions that accept any type that implements a trait:
The &impl Describe means "any type that implements Describe".
Common Derive Traits
Rust has built-in traits you can automatically implement with #[derive(...)]:
Common derive traits:
Debug— print with{:?}Clone— create copies with.clone()PartialEq— compare with==Default— create a default value
The Display Trait
To print your type with {} (not just {:?}), implement the Display trait:
Summary
| Concept | What it does |
|---|---|
trait Name { fn method(&self); } | Defines shared behavior |
impl Trait for Type { ... } | Implements the trait for a type |
| Default methods | Provide fallback implementations |
&impl Trait | Accept any type with that trait |
#[derive(Debug, Clone, PartialEq)] | Auto-implement common traits |
impl fmt::Display | Custom {} printing |
Now let's practice writing and implementing traits!