Sub topic 2
Default methods and overriding them
This chapter assumes you can define a trait and write an impl Trait for Type block, as covered in the previous chapter. It also assumes you know Rust's basic syntax for structs and methods.
What a default method is
A trait method can have a body. That body is the default method. A type that implements the trait gets the default for free, or it can write its own version.
Methods without a body are required methods. Every implementor must provide them. The compiler reports error E0046 if one is missing.
A worked example
In this example, author is required and summarize has a default body. The default calls author, so it works for any type that implements the trait.
trait Summary {
fn author(&self) -> String;
fn summarize(&self) -> String {
format!("(Read more from {}...)", self.author())
}
}
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 summarize(&self) -> String {
format!("New tweet by {}", self.author())
}
}
fn main() {
let p = Post { author: String::from("Ana") };
let t = Tweet { handle: String::from("rustlang") };
println!("{}", p.summarize());
println!("{}", t.summarize());
}The output is:
(Read more from Ana...)
New tweet by @rustlangPost leaves out summarize, so it uses the default. Tweet overrides it by defining the method with the same name and signature inside its impl block.
What defaults can and cannot do
A default body can only use what the trait itself guarantees. It can call other methods of the trait, required or default. It cannot read fields of Self, because the trait does not know what Self looks like. This is why the default summarize goes through self.author() instead of reading a field.
Overriding is all or nothing. Rust has no super call, so an override cannot call the default body it replaces. To share logic, move it into a separate required or default method that both bodies call, or into a free function.
An override must match the trait's signature exactly. That includes the parameter types and the &self or &mut self receiver.
Common errors
- E0046, missing trait item: you left out a required method. Check which methods in the trait have no body.
- E0053, incompatible signature: your override differs from the trait, for example
&mut selfwhere the trait says&self. - Reading a field in a default body: the compiler rejects it, because
Selfis unknown there. Add a required accessor method instead, asauthordoes above.
Exercise
In the Summary trait, you want Post to produce "Post by Ana" and still keep the default for other types. What do you change, and can Post's override call the default body?
Show answer
Add a summarize method to the impl Summary for Post block that returns format!("Post by {}", self.author()). Other types keep the default. The override cannot call the default body, because Rust has no super. To share the logic, move it into a helper method or function that both bodies call.