Traits and default methods
In the previous lesson, the bound T: PartialOrd required a type to be able to compare. Now let's see how such abilities are described and how you give them to your own types.
Picture a job posting: "Guard wanted. Duty: make a noise when someone comes up to the gate." The employer doesn't care who shows up: a dog, a goose or an alarm. Only one thing matters: the applicant can do what the posting lists. Each one does it their own way: the dog barks, the goose honks.
Types in a program are like this too. A dog and a cat are different structs, but both can make a noise. You want to write that ability down once and say about each type: "this one fits".
A trait and its implementation
You have already met traits as marks on a type: Copy, Debug. Now let's look inside: a trait is a named list of methods a type promises to have. It is the job posting. The list can be empty, as with Copy: such a trait only marks the type.
To "hire" a type, you write an implementation for it: an impl Trait for Type block. You already wrote such a block for Display and From in the errors theme. In the implementation each method on the list gets a body:
trait Speak {
fn speak(&self) -> String;
}
struct Dog;
impl Speak for Dog {
fn speak(&self) -> String {
String::from("woof")
}
}
fn main() {
println!("{}", Dog.speak()); // woof
}Let's go through the example line by line:
trait Speak { … }declares a trait. Inside is only the method headerfn speak(&self) -> String;, with a semicolon in place of a body: this is the duty, and each type decides how to carry it out.struct Dog;is a struct with no fields: a dog needs no data for this job.impl Speak for Dogis the implementation: the dog carries out the duties of the traitSpeak. Here the methodspeakgets a body and returns"woof".Dog.speak()calls the method with a dot, like an ordinary method fromimpl Dog, and printswoof.
A second applicant for the same job is one more implementation. Add a cat to the program:
struct Cat;
impl Speak for Cat {
fn speak(&self) -> String {
String::from("meow")
}
}
println!("{} {}", Dog.speak(), Cat.speak()); // woof meowBoth types now have a speak method, each with its own body. The trait Speak knows nothing about dogs and cats, and they know nothing about each other. Only the shared list of duties ties them together.
A default method
A job posting sometimes includes a standard instruction too: "if you have no way of your own, do it like this". A default method is a trait method that has a body in the trait itself. An implementation may leave such a method out, and then the type gets the body from the trait:
trait Speak {
fn speak(&self) -> String {
String::from("...")
}
}
struct Fish;
impl Speak for Fish {}
println!("{} {}", Fish.speak(), Dog.speak()); // ... woofLet's see what changed:
speakin the trait now has a body that returns"...";impl Speak for Fish {}is an empty implementation, and it is complete: no required methods without a body are left;Fish.speak()runs the trait's body and gives...;Dogstill writes its ownspeak, and that version replaces the default body: the program prints... woof.
A default method can call the trait's other methods, required ones included. That way one method with a body gives a type ready-made behavior, and the implementation describes only what differs from type to type.
Here the job posting picture is off. In real life, an applicant can say "I can do it" and fail. In Rust, an implementation must give a body to every method that has no default body, and the compiler checks this before anything runs.
Interviewers often ask: "How does a trait differ from an interface in Java or C#?" In short:
- a trait also describes methods a type promises to have;
- a trait's methods can have a default body;
- you can implement your own trait for someone else's type, such as
impl Speak for i32, without changingi32itself.
Common mistake
The implementation leaves out a method that has no body in the trait:
trait Speak {
fn speak(&self) -> String;
}
struct Cat;
impl Speak for Cat {} // ✗
fn main() {
println!("{}", Cat.speak());
}error[E0046]: not all trait items implemented, missing: `speak`The program does not compile: speak is declared in the trait without a body, so every implementation must write it. This is a build error, not a panic. The fix is to give speak a body in impl Speak for Cat, or a default body in the trait itself.
Key points
- A trait is a list of methods a type promises to have;
impl Trait for Typegives them bodies. - A trait method with a body is a default method: an implementation may leave it out, and the type gets the trait's body.
- An empty
impl Trait for Type {}is valid when every method of the trait has a body. - A method without a body is required in every implementation, or you get error E0046.