Sub topic 1
Defining and implementing a trait
Prerequisites
This chapter assumes you already know the following:
- Rust syntax for structs, enums, and functions.
- Ownership, borrowing, and references, including what
&selfmeans. - Basic generics, such as
Vec<T>andOption<T>. - How to build and run a small program with
cargo.
You do not need to know anything about traits yet. This chapter covers the basics. Later chapters cover bounds, dispatch, and trait objects.
What a trait is
A trait describes behavior that different types can share. It lists method signatures. Any type that implements the trait promises to provide those methods.
If you have used interfaces in Java, Go, or TypeScript, the idea is familiar. Rust differs in two ways. A type opts in explicitly with an impl block, and the compiler resolves most trait calls at compile time.
A trait is not a base class. It holds no fields and creates no inheritance hierarchy. It only describes what a type can do.
Defining a trait
You declare a trait with the trait keyword. Inside the braces, you write method signatures that end in a semicolon instead of a body.
trait Summary {
fn author(&self) -> String;
}Summary has one method, author. It takes &self, so it borrows the value it is called on, and it returns an owned String. Any type that wants to be a Summary must supply a body for author.
A trait can have any number of methods. It can also be pub if other modules or crates need to use it.
Implementing a trait for a type
You implement a trait with impl TraitName for TypeName. The block must define every method that has no default body.
trait Summary {
fn author(&self) -> String;
}
struct Post {
author: String,
}
struct Tweet {
handle: String,
}
impl Summary for Post {
fn author(&self) -> String {
self.author.clone()
}
}
impl Summary for Tweet {
fn author(&self) -> String {
format!("@{}", self.handle)
}
}
fn main() {
let p = Post { author: String::from("Ana") };
let t = Tweet { handle: String::from("rustlang") };
println!("{}", p.author());
println!("{}", t.author());
}This prints Ana and then @rustlang. The two types store their data differently, but both answer the same call.
Note that Post has a field named author and a method named author. Rust keeps fields and methods apart. self.author is the field, and self.author() is the method call.
Rules the compiler enforces
- Every required method must be present. If you leave one out, you get error E0046, "not all trait items implemented".
- Method names, parameter types, and return types must match the trait's signatures.
- You cannot add methods to the
impl Trait for Typeblock that the trait does not declare. Put extra methods in a separate inherentimpl Typeblock. - A type can implement a given trait only once (for a given set of generic arguments, covered in a later chapter).
Calling trait methods
Method call syntax such as p.author() only works when the trait is in scope. Within one file this is automatic. Across modules, you must import the trait.
mod media {
pub trait Summary {
fn author(&self) -> String;
}
pub struct Post {
pub author: String,
}
impl Summary for Post {
fn author(&self) -> String {
self.author.clone()
}
}
}
use media::{Post, Summary};
fn main() {
let p = Post { author: String::from("Ana") };
println!("{}", p.author());
}If you delete Summary from the use line, the call p.author() fails to compile. The error says the method exists but its trait is not in scope. This is a common stumbling block when code that worked in one module breaks after you move it to another.
You can also call a trait method with fully qualified syntax, which names the trait explicitly:
use media::{Post, Summary};
fn main() {
let p = Post { author: String::from("Ana") };
println!("{}", Summary::author(&p));
println!("{}", <Post as Summary>::author(&p));
}(This assumes the media module from the previous example.) The long form is needed when two traits define a method with the same name, or when the compiler cannot infer which type you mean.
Methods versus associated functions
Trait methods are not limited to &self. A trait can declare:
- Methods that take
&self,&mut self, orself. - Associated functions with no
selfparameter, which you call asType::function().
trait Zero {
fn zero() -> Self;
fn is_zero(&self) -> bool;
}
impl Zero for i32 {
fn zero() -> Self {
0
}
fn is_zero(&self) -> bool {
*self == 0
}
}
fn main() {
let z = <i32 as Zero>::zero();
println!("{} {}", z, z.is_zero());
}Self inside a trait means "the type that implements this trait". Here, zero returns whichever type is implementing Zero. Because zero takes no self, there is no value to call it on. You name the type instead.
Choose the receiver by what the method needs:
| Receiver | Meaning | Use when |
|---|---|---|
| `&self` | Read-only borrow | The method only inspects the value |
| `&mut self` | Mutable borrow | The method changes the value |
| `self` | Takes ownership | The method consumes the value |
| none | Associated function | The method builds a value or needs no instance |
Implementing a trait on existing types
You can implement your own trait for types you did not write, including built-in ones. The Zero example above does this for i32.
trait Shout {
fn shout(&self) -> String;
}
impl Shout for str {
fn shout(&self) -> String {
self.to_uppercase() + "!"
}
}
fn main() {
println!("{}", "hello".shout());
}This works because the trait is yours. The reverse is restricted. You cannot implement someone else's trait for someone else's type. That limit is the orphan rule, covered in its own chapter.
How the pieces fit together
The trait is the contract. Each impl block is a separate fulfillment of it. The compiler checks that each block matches the contract.
Common errors
- Missing method. Leaving out a required method gives E0046. Add the method or give the trait a default body.
- Trait not in scope. The method call fails even though the impl exists. Add a
usefor the trait. - Signature mismatch. If the trait says
&selfand your impl says&mut self, the compiler rejects it. Copy the signature exactly. - Wrong receiver for the job. A method that takes
selfmoves the value. Calling it twice on the same variable gives a "use of moved value" error. Use&selfunless you need to consume the value. - Ambiguous call. Two traits with the same method name on one type require fully qualified syntax.
Design notes
- Keep traits small. A trait with one or two methods is easy to implement and easy to reuse.
- Name a trait after the capability it grants, such as
SummaryorZero, not after a concrete type. - Return owned values like
Stringwhen the implementation builds new data. Return references only when the data already lives insideself, and be ready to handle lifetimes. - Implement a trait where either the trait or the type is defined, so the orphan rule is satisfied.
Exercises
Exercise
A trait Area declares fn area(&self) -> f64;. You write impl Area for Square { } with an empty body. What happens, and what is the fix?
Show answer
The compiler reports E0046 because the required method area is missing. Add fn area(&self) -> f64 { ... } inside the impl block, with a body that computes the area from the fields of Square.
Exercise
You move impl Summary for Post and a call to p.author() into different modules. The impl is still there, but the call no longer compiles. Why, and how do you fix it?
Show answer
Trait methods are callable with method syntax only when the trait is in scope. The calling module does not have Summary in scope. Fix it by adding use path::to::Summary; in the calling module, or by calling Summary::author(&p) with the full path.
Exercise
Why can Zero::zero() not be written as a method call such as value.zero()?
Show answer
zero has no self parameter, so it is an associated function and there is no receiver to call it on. You name the type instead, for example <i32 as Zero>::zero() or i32::zero().