0
0
Rustprogramming~3 mins

Why Default method implementations in Rust? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

What if you could write a method once and have it work for many types automatically?

The Scenario

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.

The Problem

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.

The Solution

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.

Before vs After
Before
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...");
    }
}
After
trait Vehicle {
    fn start(&self) {
        println!("Starting engine...");
    }
}

struct Car;
impl Vehicle for Car {}

struct Bike;
impl Vehicle for Bike {}
What It Enables

This makes your code cleaner and lets you easily share common behavior across many types without repeating yourself.

Real Life Example

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.

Key Takeaways

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.