Traits and Generics
A trait defines behaviour types can implement, like an interface. Generics with trait bounds write code that works for many types.
Example
trait Speak { fn speak(&self) -> String; }
struct Dog;
struct Cat;
impl Speak for Dog { fn speak(&self) -> String { "Woof".to_string() } }
impl Speak for Cat { fn speak(&self) -> String { "Meow".to_string() } }
fn talk<T: Speak>(t: &T) { println!("{}", t.speak()); }
fn main() {
talk(&Dog);
talk(&Cat);
}Result
Woof Meow
Exercise
Define shared behaviour.
Speak { }Quiz Test
These free lessons are for learning. Join a full course for projects, mentor feedback and a verified certificate.