Rust Default methods


Example

trait Speak {
    fn speak(&self) -> String {
        String::from("Hi.")
    }
}

The method will be called by default except if it's overwritten in the impl block.

struct Human;
struct Cat;

impl Speak for Human {}

impl Speak for Cat {
    fn speak(&self) -> String {
        String::from("Meow.")
    }
}

fn main() {
    let human = Human {};
    let cat = Cat {};
    println!("The human says {}", human.speak());
    println!("The cat says {}", cat.speak());
}

Output :

The human says Hi.

The cat says Meow.