A Rust trait describes a capability a type can provide. Think of it as a qualification: different types can earn the same qualification, while each still has its own features. Implementing a trait for a type gives that type the trait’s methods. section 7.1 section 7.6
A trait can provide a default method, or declare only a method signature—the method’s name, inputs, and output. When a trait supplies only a signature, each type implementing it must write the method. Use a default when most types should behave the same way; use a signature when they need their own behavior. section 7.1.1
struct Animal {
name: String,
}
trait DogLike {
fn bark(&self); #1
fn run(&self);
}
impl DogLike for Animal {
fn bark(&self) {
println!("{}, stop barking!!", self.name);
}
fn run(&self) {
println!("{} is running!", self.name);
}
}
fn main() {
let rover = Animal {
name: "Rover".to_string(),
};
rover.bark();
rover.run();
}
DogLike declares two method signatures. The impl block supplies both methods for Animal, so an Animal can call them. section 7.1.1
Some common traits can be implemented automatically with an attribute such as #[derive(Debug)]. Others need an impl block because Rust cannot guess the desired behavior. For example, adding two values of a custom type might reasonably produce several different results. section 7.1
Display and Debug
Display controls formatting with {}, while Debug uses {:?} or {:#?}. If the compiler says a type does not implement Display, it may suggest trying Debug instead. You can also implement Display for your own type to choose its output. section 1.8 section 7.1.1
use std::fmt;
struct Cat {
name: String,
age: u8,
}
impl fmt::Display for Cat {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{} is a cat who is {} years old", self.name, self.age)
}
}
fn main() {
let mr_mantle = Cat {
name: "Reggie Mantle".to_string(),
age: 4,
};
println!("{mr_mantle}");
}
This implementation gives Cat its own Display formatting, so println! can print it with {}. section 7.1.1
A trait can also be a bound: a requirement that a type supplied to a function implement a particular trait. More bounds give the function more capabilities to rely on, but fewer types will satisfy all the requirements. section 7.1.4 section 5.3
There is a limit on implementations: you can implement your own trait for someone else’s type, or someone else’s trait for your own type, but not someone else’s trait for someone else’s type. When using a trait, check its documentation for required methods; Iterator requires next(), for example. section 7.6 section 13.1.4



