Rust Traits
Traits
In the Methods chapter, you learned how to add methods to a struct with impl.
Sometimes different structs should be able to do the same thing. For example, a dog and a cat can both make a sound, but each animal makes its own sound.
A trait describes behavior (methods) that different types can share. If you know Java or C#, a trait is similar to an interface.
Create a Trait
To create a trait, use the trait keyword, followed by a name. Inside the curly braces, write the first line of each method that the types must have, followed by a semicolon:
Example
trait Animal {
fn make_sound(&self);
}
This trait says: "Every type that is an Animal must have a make_sound() method". It does not say what the method does.
Implement a Trait
To give a struct the behavior of a trait, write impl TraitName for StructName, and put the method inside:
Example
trait Animal {
fn make_sound(&self);
}
struct Dog {
name: String,
}
struct Cat {
name: String,
}
impl Animal for Dog {
fn make_sound(&self) {
println!("{} says woof!", self.name);
}
}
impl Animal for Cat {
fn make_sound(&self) {
println!("{} says meow!", self.name);
}
}
fn main() {
let dog = Dog { name: String::from("Buddy") };
let cat = Cat { name: String::from("Kitty") };
dog.make_sound();
cat.make_sound();
}
Try it Yourself »
Both Dog and Cat now have a make_sound() method. Each struct decides what its own method does.
All Methods Are Required
A struct that implements a trait must have all the methods that the trait lists. If one is missing, the program will not compile:
Example
trait Animal {
fn make_sound(&self);
}
struct Cat {
name: String,
}
impl Animal for Cat {
} // Error: make_sound() is missing
Try it Yourself »
The error message tells you what is missing: not all trait items implemented, missing: make_sound.
Default Methods
A trait can also give a method a default body. Types that implement the trait get the default method automatically, but they can also write their own version of it:
Example
trait Greet {
fn hello(&self) {
println!("Hello!");
}
}
struct Student {
name: String,
}
struct Teacher {
name: String,
}
impl Greet for Student {}
impl Greet for Teacher {
fn hello(&self) {
println!("Good morning, class!");
}
}
fn main() {
let student = Student { name: String::from("Liam") };
let teacher = Teacher { name: String::from("Jenny") };
print!("{}: ", student.name);
student.hello();
print!("{}: ", teacher.name);
teacher.hello();
}
Try it Yourself »
Student uses the default hello() method, because its impl block is empty. Teacher replaces it with its own version.
Traits as Parameters
You can write a function that accepts any type that implements a trait. Use &impl TraitName as the parameter type:
Example
fn introduce(animal: &impl Animal) {
println!("Listen:");
animal.make_sound();
}
fn main() {
let dog = Dog { name: String::from("Buddy") };
let cat = Cat { name: String::from("Kitty") };
introduce(&dog);
introduce(&cat);
}
Try it Yourself »
The introduce() function works with both a dog and a cat. It only needs something that can make_sound().
Traits You Have Already Used
You have used traits before, without knowing it. When you print a vector with {:?}, Rust uses the Debug trait, which vectors and arrays already have.
Your own structs do not have it. Add #[derive(Debug)] above the struct, and Rust writes the Debug code for you:
Example
#[derive(Debug)]
struct Point {
x: i32,
y: i32,
}
fn main() {
let p = Point { x: 3, y: 7 };
println!("{:?}", p);
}
Try it Yourself »
Without #[derive(Debug)], the println! line gives an error, because Point does not implement Debug.
Why Use Traits?
- To give different types the same behavior
- To write functions that work with many types
- To share code with default methods