0
0
Rustprogramming~5 mins

Default method implementations in Rust

Choose your learning style9 modes available
Introduction

Default method implementations let you write a method once and reuse it in many places. This saves time and keeps your code simple.

When you want to provide a common behavior for many types but allow them to change it if needed.
When you create a trait and want to give a default way to do something.
When you want to avoid repeating the same code in every type that uses a trait.
Syntax
Rust
trait TraitName {
    fn method_name(&self) {
        // default implementation
    }
}

Methods inside traits can have a default body.

Types implementing the trait can use the default or provide their own version.

Examples
This trait has a method with a default message.
Rust
trait Greet {
    fn say_hello(&self) {
        println!("Hello!");
    }
}
Person uses the default greeting from the trait.
Rust
struct Person;

impl Greet for Person {}

fn main() {
    let p = Person;
    p.say_hello();
}
Dog provides its own greeting, replacing the default.
Rust
struct Dog;

impl Greet for Dog {
    fn say_hello(&self) {
        println!("Woof!");
    }
}

fn main() {
    let d = Dog;
    d.say_hello();
}
Sample Program

This program shows a trait Animal with a default method sound. Cat uses the default sound, while Cow provides its own sound.

Rust
trait Animal {
    fn sound(&self) {
        println!("Some sound");
    }
}

struct Cat;
struct Cow;

impl Animal for Cat {}

impl Animal for Cow {
    fn sound(&self) {
        println!("Moo");
    }
}

fn main() {
    let cat = Cat;
    let cow = Cow;

    cat.sound();  // uses default
    cow.sound();  // uses custom
}
OutputSuccess
Important Notes

Default methods help avoid repeating code.

You can always override the default by writing your own method.

Traits with default methods make your code flexible and easier to maintain.

Summary

Default method implementations provide reusable behavior in traits.

Types can use the default or override it with their own method.

This feature keeps code clean and reduces repetition.