Sub topic 1
Defining and Implementing a Trait
A trait describes behavior that different types can share. This chapter covers how to declare a trait, implement it for your own types, and call its methods.
Prerequisites
This chapter assumes you know the following:
- Rust syntax for structs, enums, and functions.
- Ownership, borrowing, and references, including
&self. - Basic generics such as
Vec<T>andOption<T>. - How to build and run a small program with
cargo.
What a trait is
A trait is a named set of method signatures. A type that provides those methods can implement the trait. Code that only needs the behavior can then work with any such type.
Here is a trait with one method, and two types that implement it.
trait Speak {
fn speak(&self) -> String;
}
struct Dog;
struct Robot {
id: u32,
}
impl Speak for Dog {
fn speak(&self) -> String {
String::from("Woof")
}
}
impl Speak for Robot {
fn speak(&self) -> String {
format!("Unit {} online", self.id)
}
}
fn main() {
let d = Dog;
let r = Robot { id: 7 };
println!("{}", d.speak());
println!("{}", r.speak());
}The trait declares only the signature, ending in a semicolon. Each impl Trait for Type block supplies the body. The signature in the impl must match the one in the trait.
How an implementation works
An impl Speak for Dog block does three things:
- It names the trait and the type.
- It must define every method that has no default body.
- It makes the methods callable with dot syntax, such as
d.speak().
The trait must be in scope to call its methods. If the trait lives in another module, bring it in with use.
mod animals {
pub trait Speak {
fn speak(&self) -> String;
}
pub struct Cat;
impl Speak for Cat {
fn speak(&self) -> String {
String::from("Meow")
}
}
}
use animals::{Cat, Speak};
fn main() {
println!("{}", Cat.speak());
}Without use animals::Speak, the call Cat.speak() fails with an error saying the method exists but the trait is not in scope.
Common errors
| Mistake | What the compiler says |
|---|---|
| Leaving out a required method | `not all trait items implemented, missing: ...` |
| Different signature than the trait | `method has an incompatible type for trait` |
| Trait not imported | `items from traits can only be used if the trait is in scope` |
| Method defined outside the `impl` block | The method is an ordinary inherent method, and the trait is not satisfied. |
Keep methods in the impl Trait for Type block when you want them to count as part of the trait. Methods in a plain impl Type block are separate and do not satisfy a trait.
The shape of the whole flow
Later chapters build on this. Default methods let a trait provide a body so implementors can skip some methods. Trait bounds let generic functions accept any type that implements a trait.
Exercise
You write impl Speak for Dog { } with an empty body, and the trait Speak declares fn speak(&self) -> String; with no default body. What happens when you compile, and how do you fix it?
Show answer
The compiler reports that not all trait items are implemented, because speak is missing. Fix it by adding fn speak(&self) -> String { ... } inside the impl Speak for Dog block.
Exercise
You call Cat.speak() in a different module from the one that defines the Speak trait, and the compiler says the method is not found. What is the likely cause?
Show answer
The Speak trait is not in scope. Add use for the trait, for example use animals::Speak;, so its methods can be called.