Rust Traits
A trait describes a set of behaviour that a type promises to provide. If you know interfaces from Java or C#, traits will feel familiar: a trait lists method signatures, and any type that implements the trait must supply those methods. Traits are how Rust shares behaviour between unrelated types without inheritance.
Defining and implementing a trait
Use the trait keyword to declare the methods, then impl TraitName for TypeName to fill them in for a particular type.
trait Describe {
fn describe(&self) -> String;
}
struct Planet {
name: String,
moons: u32,
}
struct Book {
title: String,
pages: u32,
}
impl Describe for Planet {
fn describe(&self) -> String {
format!("{} has {} moon(s)", self.name, self.moons)
}
}
impl Describe for Book {
fn describe(&self) -> String {
format!("'{}' is {} pages long", self.title, self.pages)
}
}
fn main() {
let mars = Planet { name: String::from("Mars"), moons: 2 };
let novel = Book { title: String::from("The Long Road"), pages: 320 };
println!("{}", mars.describe());
println!("{}", novel.describe());
}Mars has 2 moon(s)
'The Long Road' is 320 pages long
Planet and Book have nothing in common except that both now implement Describe. That shared promise is what lets us write code that works with either of them.
Default methods
A trait can provide a default implementation for a method. Types get it for free, but may override it if they want something different. Default methods can even call the other, required methods of the trait.
trait Greeter {
fn name(&self) -> String;
fn greet(&self) -> String {
format!("Hello, {}!", self.name())
}
}
struct Robot;
struct Pirate;
impl Greeter for Robot {
fn name(&self) -> String {
String::from("unit 7")
}
}
impl Greeter for Pirate {
fn name(&self) -> String {
String::from("Captain Kidd")
}
fn greet(&self) -> String {
format!("Ahoy, I be {}!", self.name())
}
}
fn main() {
println!("{}", Robot.greet());
println!("{}", Pirate.greet());
}Hello, unit 7!
Ahoy, I be Captain Kidd!
Robot only wrote name and used the default greet; Pirate replaced greet with its own version.
Traits as parameters
The real power of traits shows up when a function accepts any type that implements a trait. There are two common ways to write that:
| Syntax | Example | Notes |
|---|---|---|
impl Trait |
fn show(item: &impl Describe) |
Short and readable |
| Trait bound | fn show<T: Describe>(item: &T) |
Same meaning, more flexible |
where clause |
fn show<T>(item: &T) where T: Describe |
Tidy when there are many bounds |
| Trait object | fn show(item: &dyn Describe) |
Type decided at run time |
The first three are resolved at compile time (the compiler makes a copy of the function for each concrete type). dyn Trait uses a trait object, which lets you mix different types in one collection, such as Vec<Box<dyn Shape>>.
trait Shape {
fn area(&self) -> f64;
fn label(&self) -> &str;
}
struct Square { side: f64 }
struct Circle { radius: f64 }
impl Shape for Square {
fn area(&self) -> f64 { self.side * self.side }
fn label(&self) -> &str { "square" }
}
impl Shape for Circle {
fn area(&self) -> f64 { 3.14 * self.radius * self.radius }
fn label(&self) -> &str { "circle" }
}
fn report(shape: &impl Shape) {
println!("A {} with area {:.2}", shape.label(), shape.area());
}
fn main() {
report(&Square { side: 3.0 });
let shapes: Vec<Box<dyn Shape>> = vec![
Box::new(Square { side: 2.0 }),
Box::new(Circle { radius: 1.0 }),
];
let mut total = 0.0;
for s in &shapes {
total += s.area();
}
println!("Total area of {} shapes: {:.2}", shapes.len(), total);
}A square with area 9.00
Total area of 2 shapes: 7.14
Deriving and implementing standard traits
The standard library defines many traits you will use every day. Some can be generated automatically with #[derive(...)]; others, like Display, you implement yourself.
| Trait | Gives you |
|---|---|
Debug |
{:?} formatting |
Clone |
.clone() to make a deep copy |
PartialEq |
== and != |
PartialOrd |
<, >, <=, >= |
Default |
Type::default() |
Display |
{} formatting (implement by hand) |
use std::fmt;
#[derive(Debug, Clone, PartialEq)]
struct Point {
x: i32,
y: i32,
}
impl fmt::Display for Point {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "({}, {})", self.x, self.y)
}
}
fn main() {
let a = Point { x: 4, y: -1 };
let b = a.clone();
println!("Debug: {:?}", a);
println!("Display: {}", a);
println!("Equal? {}", a == b);
}Debug: Point { x: 4, y: -1 }
Display: (4, -1)
Equal? true
Tip: Deriving
Debugon almost every struct you write is a good habit — it makes printing values while debugging effortless.
Test yourself
What does a default method in a trait allow?
- Types must always override it
- Types get the method for free but may override it
- The method can only be called on primitive types
- The trait cannot have other methods
Which syntax lets you store different types that implement Shape in one vector?
Vec<impl Shape>Vec<Shape>Vec<Box<dyn Shape>>Vec<T: Shape>
Which trait must you implement to print a value with {}?
DebugDisplayCloneToString