Traits
A trait names a set of methods a type can implement. It is Rust's tool for shared behaviour and for generic bounds, not a class you inherit from.
Detailed Explanation
trait Greet { fn greet(&self); } is a contract. impl Greet for Session { fn greet(&self) { ... } } is a type signing that contract. After that, any function that wants "something greetable" writes T: Greet or takes impl Greet or &dyn Greet.
Traits hold method signatures, default method bodies, associated types, and associated constants. A default body lets implementors skip boilerplate: PartialEq can define ne in terms of eq. Required methods have no default; each implementor must write them. Associated types let the implementor pick a related type once, as Iterator::Item, instead of parameterising every use with an extra generic.
Supertraits are bounds, not parent classes. trait Print: Display { } means you cannot implement Print unless the type already implements Display. You do not inherit Display's methods through a vtable of Print; you just cannot form the impl otherwise.
The orphan rule keeps impls coherent: you implement a trait for a type only if you own at least one of them. That stops two crates from shipping conflicting impl Serialize for DateTime. The usual escape is a newtype in your crate.
Trait methods are in scope only when the trait itself is in scope. buf.write_all(b"hi") fails with "no method named write_all" until you use std::io::Write. This is how extension traits work: a trait in your crate adds methods to str or Iterator, and they appear only after the use of that trait.
Three ways to use a trait at a call site: static dispatch via a generic bound, static dispatch via impl Trait in argument position, and dynamic dispatch via dyn Trait. Start with the generic bound. Reach for dyn when you need mixed types in one collection or want to keep the generic type out of your public API.
When you write a trait: two or more types should answer the same question, or you are defining an extension surface. When one type owns the behaviour, an inherent impl is enough.
Code Examples
trait Greet {
fn greet(&self);
}
struct User {
name: String,
}
impl Greet for User {
fn greet(&self) {
println!("hello {}", self.name);
}
}
fn hello(g: &impl Greet) {
g.greet();
}
fn main() {
hello(&User { name: "Ada".into() }); // prints: hello Ada
}Common Gotchas
The trait must be in scope to call its methods
`use std::io::Write;` before `file.write_all`. The type can implement the trait and still hide the methods.
Orphan rule
You cannot implement a foreign trait for a foreign type. Wrap the type.
Default methods can silently do nothing useful
Read the default body before you rely on it. Required methods are the ones you must think about.
Supertraits are bounds
`trait A: B` does not copy `B`'s fields or create a class tree. It only requires `B` to be implemented first.