Rust Fundamentals · 15 XP Pro
Default methods
A trait can supply a body for a method. Types that implement the trait get that behaviour for free, and may override it if they need something different. Default methods can call the trait's other methods, so they build on whatever the implementor must provide.
pub trait Animal {
fn name(&self) -> String; // required
fn intro(&self) -> String { // default
format!("I am {}", self.name())
}
}
An impl Animal for Dog only has to write name; writing intro as well
replaces the default.
Your task
The starter has the trait and two structs with placeholder bodies. Everything
must stay pub, because the tests use your crate as lesson.
- In trait
Greeter, givegreetthe default bodyformat!("Hello, {}!", self.name()). Person { pub name: String }:namereturns a clone of the field. Do not writegreet; it should use the default.Robot { pub id: u32 }:namereturnsformat!("Robot-{}", self.id), and overridegreetto returnformat!("BEEP {}", self.id).
Remove the todo!() calls and write the override only where it is needed.