Traits
A trait defines shared behaviour. Types implement it with impl Trait for Type.
Example
trait Speak { fn say(&self) -> String; }
struct Dog; struct Cat;
impl Speak for Dog { fn say(&self) -> String { "Woof".into() } }
impl Speak for Cat { fn say(&self) -> String { "Meow".into() } }
fn main() {
let a: Vec<Box<dyn Speak>> = vec![Box::new(Dog), Box::new(Cat)];
for s in &a { println!("{}", s.say()); }
}Result
Woof Meow
Exercise
Trait keyword.
Speak { fn say(&self) -> String; }Quiz Test
These free lessons are for learning. Join a full course for projects, mentor feedback and a verified certificate.