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.

  1. In trait Greeter, give greet the default body format!("Hello, {}!", self.name()).
  2. Person { pub name: String }: name returns a clone of the field. Do not write greet; it should use the default.
  3. Robot { pub id: u32 }: name returns format!("Robot-{}", self.id), and override greet to return format!("BEEP {}", self.id).

Remove the todo!() calls and write the override only where it is needed.

Next lesson →

Sign in to run your code. It's free.