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. You should also be comfortable with &self receivers and String formatting.
What a default method is
A trait method can have a body. When it does, every implementor gets that method without writing it. The implementor can still replace the body with its own.
A trait therefore has two kinds of methods:
| Kind | Declared as | Implementor must write it? |
|---|---|---|
| Required method | `fn author(&self) -> String;` | Yes |
| Default method | `fn summarize(&self) -> String { ... }` | No, but may |
Default methods let a trait offer a large, convenient interface while asking implementors for only a few primitive operations. The standard library's Iterator trait has one required method, next, and dozens of default methods built on it.
A worked example
The trait below has one required method and one default method. Post accepts the default. Tweet overrides it.
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());
}This prints:
(Read more from Ana...)
New tweet by @rustlangThe default body of summarize calls self.author(). The compiler checks that body once, against the trait, so it can only use what the trait guarantees about Self. It knows author exists, because it is declared in the trait. It does not know that Self has a field named author, and it cannot read fields at all. Default methods work through other trait methods.
How the compiler picks a body
When you call x.summarize(), the compiler looks in the impl Summary for X block. If the block defines summarize, that body is used. Otherwise the trait's default is used.
The default body is shared, but the calls it makes on self resolve per type. That is why Post and Tweet can share a default body and still print different author text.
Overriding rules and gotchas
An override replaces the default completely
Rust has no super call. Inside an override you cannot say "run the default body, then add more." If you want both, move the shared logic into a free function or a separate method, and call it from both places.
trait Greeter {
fn name(&self) -> String;
fn greet(&self) -> String {
default_greeting(&self.name())
}
}
fn default_greeting(name: &str) -> String {
format!("Hello, {name}!")
}
struct Casual(String);
struct Formal(String);
impl Greeter for Casual {
fn name(&self) -> String {
self.0.clone()
}
}
impl Greeter for Formal {
fn name(&self) -> String {
self.0.clone()
}
fn greet(&self) -> String {
format!("{} Good day.", default_greeting(&self.name()))
}
}
fn main() {
println!("{}", Casual(String::from("Sam")).greet());
println!("{}", Formal(String::from("Dr. Lee")).greet());
}An override must keep the signature
The override must match the trait's signature: the same receiver, parameter types, and return type. You cannot change &self to &mut self or return a different type. The compiler rejects the impl if you try.
You cannot override part of a method
You override a whole method or none of it. You also cannot remove a default. An implementor who does not want the behavior has to override it with something else, such as unimplemented!(). That is a sign the trait is shaped poorly, so consider splitting it.
Required methods can be mistaken for defaults
If you forget a required method, the compiler reports error E0046, "not all trait items implemented." If a method has a default, forgetting it is never an error. This matters when you add a default to a trait that others implement: their code keeps compiling. Adding a default method is generally a backward-compatible change for implementors. Adding a required method breaks them.
Name clashes between traits
Default methods enlarge the set of method names a type has. If two traits in scope give a type the same method name, a plain call is ambiguous and fails to compile. Name the trait explicitly:
trait Pilot {
fn fly(&self) -> String {
String::from("This is your captain.")
}
}
trait Wizard {
fn fly(&self) -> String {
String::from("Up!")
}
}
struct Human;
impl Pilot for Human {}
impl Wizard for Human {}
fn main() {
let h = Human;
println!("{}", Pilot::fly(&h));
println!("{}", <Human as Wizard>::fly(&h));
}Pilot::fly(&h) works because the argument tells the compiler which type to use. The longer form <Human as Wizard>::fly(&h) is the fully qualified syntax. You need it when a function has no self argument to infer from.
Default methods and trait objects
Default methods are available through dyn Trait. A call on Box<dyn Summary> runs the override if one exists, and the default otherwise. The choice is made at run time through the vtable, which holds an entry for every method, including defaults.
Some default methods cannot be part of a trait object. A method that takes self by value, or has its own generic type parameter, is not callable on dyn Trait. Adding where Self: Sized excludes just that method from the trait object. The rest of the trait stays usable as dyn.
trait Shape {
fn area(&self) -> f64;
fn scaled_area(self, k: f64) -> f64
where
Self: Sized,
{
self.area() * k * k
}
}
struct Square(f64);
impl Shape for Square {
fn area(&self) -> f64 {
self.0 * self.0
}
}
fn main() {
let boxed: Box<dyn Shape> = Box::new(Square(1.0));
println!("{}", boxed.area());
println!("{}", Square(2.0).scaled_area(2.0));
}Without the where Self: Sized clause, Shape could not be used as dyn Shape at all. Later chapters cover the full rules.
Why override a default
There are two common reasons to override:
- Different behavior.
Tweetwants its own wording. - Better performance. The default may be correct but slow, because it can only use the required methods.
Iterator::nthdefaults to callingnextrepeatedly. A type backed by a slice can jump straight to the element, so it overridesnth.
When you override for performance, the result must match what the default would produce. Callers rely on the trait's documented behavior, not on which body runs.
Design guidance
- Keep the required set small. Each required method is work for every implementor.
- Write defaults in terms of the required methods, so the default stays correct for every type.
- Document which methods are meant to be overridden and which are conveniences.
- Do not give a default to a method whose sensible behavior depends on the type. Make it required.
Exercise
A trait Logger has a required method fn name(&self) -> String and a default method fn log(&self, msg: &str) -> String that returns format!("[{}] {}", self.name(), msg). A type Db implements only name. Which body runs for Db.log("ok")? Then, an implementor wants log to add a timestamp before the default output. How should it do this, given that Rust has no super call?
Show answer
The trait's default body runs, because Db does not define log. It calls Db's name. For the timestamp, Rust cannot call the default from inside an override. Move the shared formatting into a free function (or a separate trait method) that both the default and the override call, then have the override build its output from that function plus the timestamp.
Exercise
Why is adding a new default method to a published trait usually a compatible change, while adding a new required method is not? What can still break in the default-method case?
Show answer
Existing implementors do not define the new default method, so their impl blocks stay valid and compile unchanged. A new required method makes every existing impl incomplete (error E0046). A default can still break callers if its name clashes with a method of the same name from another trait in scope, which makes plain method calls ambiguous.