Medium
A trait default method with one implementor overriding it
What does this program print?
main.rs
trait Greet {
fn name(&self) -> String;
fn greeting(&self) -> String {
format!("Hello, {}!", self.name())
}
}
struct Person {
name: String,
}
impl Greet for Person {
fn name(&self) -> String {
self.name.clone()
}
}
struct Robot {
id: u32,
}
impl Greet for Robot {
fn name(&self) -> String {
format!("Unit-{}", self.id)
}
fn greeting(&self) -> String {
format!("BEEP BOOP {} ONLINE", self.name().to_uppercase())
}
}
fn main() {
let p = Person { name: "Ada".to_string() };
let r = Robot { id: 7 };
println!("{}", p.greeting());
println!("{}", r.greeting());
}20 of 53 in Rust