What if you could write a method once and have it work for many types automatically?
Why Default method implementations in Rust? - Purpose & Use Cases
Imagine you have many types of vehicles, and you want each to have a method to start the engine. Without default methods, you must write the same start code for every vehicle type manually.
This manual approach is slow and repetitive. If you want to change how starting works, you must update every vehicle's code separately, which is error-prone and tiring.
Default method implementations let you write the common start code once in a shared place. Each vehicle type can use this default or provide its own version if needed, saving time and reducing mistakes.
trait Vehicle {
fn start(&self);
}
struct Car;
impl Vehicle for Car {
fn start(&self) {
println!("Starting engine...");
}
}
struct Bike;
impl Vehicle for Bike {
fn start(&self) {
println!("Starting engine...");
}
}trait Vehicle {
fn start(&self) {
println!("Starting engine...");
}
}
struct Car;
impl Vehicle for Car {}
struct Bike;
impl Vehicle for Bike {}This makes your code cleaner and lets you easily share common behavior across many types without repeating yourself.
Think of a game where many characters can attack. You can provide a default attack method, and only special characters need to write their own unique attack.
Default methods reduce repeated code by providing shared behavior.
They make updates easier since you change code in one place.
Types can still customize behavior by overriding defaults.