預設方法

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

預設情況下將呼叫該方法,除非它在 impl 塊中被覆蓋。

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());
}

輸出:

人類說嗨。

貓說喵。