默认方法
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());
}
输出:
人类说嗨。
猫说喵。