Rust Fundamentals · 15 XP Pro

Defining traits

A trait describes behaviour that different types can share. It lists method signatures; each type then provides its own body in an impl Trait for Type block.

pub trait Speak {
    fn sound(&self) -> String;
}

pub struct Cat;
pub struct Cow;

impl Speak for Cat {
    fn sound(&self) -> String { "meow".to_string() }
}
impl Speak for Cow {
    fn sound(&self) -> String { "moo".to_string() }
}

Any type that implements the trait can be used wherever that behaviour is needed, and cat.sound() is called like any other method.

Your task

Everything must be pub (the trait, the structs and their fields), because the tests use your crate as lesson.

  1. Define pub trait Shape with one required method fn area(&self) -> f64;.
  2. Define pub struct Rect { pub width: f64, pub height: f64 } and implement Shape for it (width times height).
  3. Define pub struct Circle { pub radius: f64 } and implement Shape for it (std::f64::consts::PI * radius * radius).

Next lesson →

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