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.
- Define
pub trait Shapewith one required methodfn area(&self) -> f64;. - Define
pub struct Rect { pub width: f64, pub height: f64 }and implementShapefor it (width times height). - Define
pub struct Circle { pub radius: f64 }and implementShapefor it (std::f64::consts::PI * radius * radius).