In Rust, how does a trait give a method a default body, and what happens when an implementing type overrides it?
answer
- signature with a block
- default calls required methods
- same syntax to override
- no super call to the default
basics
~20 sA trait method written with a body is a default: implementors inherit it unless their impl defines the same method, which replaces it completely. Defaults may call required methods; an override cannot call the default it replaced.
solid answer
~40 sIn a trait, a signature ending in `;` is a **required** method and a signature followed by a block is a **default** (provided) method. `impl Notifier for EmailNotifier` must define every required method (E0046 otherwise) and may omit the defaults, which then run as written, with calls like `self.send(msg)` resolving to that type's own `send`. Overriding uses exactly the same syntax as implementing a required method, and the new body replaces the default for that type only. There is no `super`-style call: the Rust Book states it is not possible to call the default from an overriding implementation of the same method, and writing `Notifier::retry(self, ..)` inside the override just calls the override again. Shared logic goes into a separate trait method or a free function that both bodies call.
code
rust · 40 linestrait Notifier {
fn send(&self, msg: &str) -> Result<(), String>;
fn retry(&self, msg: &str, attempts: u32) -> Result<(), String> {
let mut last = Err(String::from("no attempts"));
for _ in 0..attempts {
last = self.send(msg);
if last.is_ok() {
break;
}
}
last
}
}
struct EmailNotifier;
struct SmsNotifier;
impl Notifier for EmailNotifier {
fn send(&self, msg: &str) -> Result<(), String> {
println!("email: {msg}");
Ok(())
}
}
impl Notifier for SmsNotifier {
fn send(&self, msg: &str) -> Result<(), String> {
Err(format!("sms gateway down: {msg}"))
}
// Overrides the default: SMS is billed per message, so send once.
fn retry(&self, msg: &str, _attempts: u32) -> Result<(), String> {
self.send(msg)
}
}
fn main() {
println!("{:?}", EmailNotifier.retry("disk full", 3));
println!("{:?}", SmsNotifier.retry("disk full", 3));
}go deeper
Recall the two shapes: a signature ending in a semicolon is required, a signature with a body is a default that implementors may skip or replace with the same syntax.
Explain that a default body calls the trait's required methods and resolves them per implementing type, and that it cannot see fields, so data must come through required methods.
Show you know an override replaces the default wholesale, that Notifier::retry inside the override recurses, and how you would restructure shared logic so both bodies reuse it.
Frame default methods as the tool for keeping implementor burden small while letting a trait grow, and be ready to say what a reviewer should check when a default is overridden.
## What a trait declares A **trait** in Rust names behaviour that a type promises to provide: a set of methods, plus optionally associated types and constants. A notification system might declare: ```rust trait Notifier { fn send(&self, msg: &str) -> Result<(), String>; fn retry(&self, msg: &str, attempts: u32) -> Result<(), String> { let mut last = Err(String::from("no attempts")); for _ in 0..attempts { last = self.send(msg); if last.is_ok() { break; } } last } } ``` Two kinds of method appear here: - A **required method** is a signature that ends in a semicolon, like `send`. Every implementing type must write its body. - A **provided** or **default method** is a signature followed by a block, like `retry`. Implementing types get it for free. Inside the trait, `Self` means "whichever type implements this trait", and `&self` is shorthand for `self: &Self`. The trait knows nothing else about that type. ## Implementing the trait An implementation is a block `impl Notifier for EmailNotifier { ... }`. rustc 1.99.1 enforces a few rules on it: 1. Every required method must be defined. Leaving `send` out fails with E0046, `not all trait items implemented, missing: `send``. 2. The block may contain only items the trait declares. Adding a helper `fn ping(&self)` fails with E0407, `method `ping` is not a member of trait `Notifier``; helpers belong in an inherent block, `impl EmailNotifier { ... }`. 3. Each method's signature must be compatible with the trait's declaration; taking `String` where the trait says `&str` fails with E0053, `method `send` has an incompatible type for trait`. 4. Default methods may be left out, in which case the type uses the default body. ## How a default body works A default body can call any other method of the same trait, **including required methods that have no body yet**. That is the main design pattern: the trait asks implementors for a small core (`send`) and builds richer behaviour on top of it (`retry`). When `EmailNotifier` uses the default `retry`, the `self.send(msg)` inside it calls `EmailNotifier`'s own `send`; for another type it calls that type's `send`. The call is resolved statically for each implementing type. What a default body **cannot** do is reach into the implementing type's data. A trait has no fields, so the default sees only what the trait (and any supertrait) declares. If a default needs a value such as a recipient address, the trait has to expose it through a required method like `fn recipient(&self) -> &str`. ## Overriding a default Overriding uses **the same syntax** as implementing a required method: write `fn retry(...)` inside the impl. The new body replaces the default for that one type; every other type keeps the default. In the snippet below, `SmsNotifier` overrides `retry` because each text message is billed, so it sends once instead of looping. There is no equivalent of calling a parent class's version. The Rust Book says plainly that it is not possible to call the default implementation from an overriding implementation of that same method. The tempting workaround does not work: - Writing `Notifier::retry(self, msg, n)` inside the override names the trait method **for this type**, which is now the override, so it recurses forever. rustc 1.99.1 warns `function cannot return without recursing` (the `unconditional_recursion` lint), but it still compiles. - The fix is to move the shared logic out: a second default method such as `retry_with_backoff`, or a free function taking `&impl Notifier`, which both the default `retry` and the override can call. ## Required and default methods side by side | Aspect | Required method | Default method | |---|---|---| | Written in the trait as | signature ending in `;` | signature with a `{ ... }` body | | Implementor must write it | yes, or E0046 | no | | Implementor may replace it | it always writes its own | yes, same syntax | | Can call other trait methods | in each impl's body | yes, including required ones | | Can read the type's fields | yes, inside the concrete impl | no, the trait has no fields | ## Why this matters in practice Default methods let a trait grow useful behaviour while keeping the implementation burden small: two notifier types write one method each and share the retry loop. They also make a trait easier to extend later, because a new method with a default body does not force every existing implementor to change. (Whether such an addition is fully safe for downstream users is a semver question covered with API evolution.) The cost to remember is that an override is all-or-nothing: if a type wants "the default plus a little extra", the default's logic must live somewhere both bodies can call.
- Inside an override of `retry`, what happens if you write `Notifier::retry(self, msg, n)` to reuse the default?It calls the override itself, because for this type `Notifier::retry` now means the overriding body. The result is infinite recursion; rustc warns `function cannot return without recursing` but compiles it. Rust offers no way to reach the replaced default, so put the shared loop in another trait method or a free function and call that from both places.
- Can a default method in `Notifier` read a field such as `address` that every implementor happens to have?No. A trait has no fields and knows nothing about the implementing type's layout; a default body sees only the methods the trait and its supertraits declare. Expose the value through a required method such as `fn recipient(&self) -> &str`, and let each impl return its own field.
- What does rustc do if `impl Notifier for EmailNotifier` adds a method `ping` that the trait does not declare?It rejects the impl with E0407, `method `ping` is not a member of trait `Notifier``. A trait impl may only define the trait's own items; type-specific helpers go in an inherent `impl EmailNotifier` block.
A company procedure manual with one blank step: every office must write its own "contact the customer" step, and inherits the standard "try three times, then escalate" step unless it writes its own version, which then replaces the standard one outright rather than wrapping it.
- An override can call the default body with something like super.retry().
- A default method can read the implementing struct's fields directly.
- Every trait method must be implemented by every type, defaults or not.
- Overriding a default needs a special keyword such as override.
- A trait impl can add extra helper methods the trait does not declare.