When should you use a trait as a type in rust?
I recently started learning rust and I learned traits are valid types in rust. I thought this was pretty neat, so I made a little example program. What exactly is the point of having a trait as a type if it has very similar and or the same functionality as a method and also comes with the costs of
- Must be wrapped in Box making it always heap allocated instead of stack allocated
- Has an expensive initialization cost
I'm new to rust and don't 100% understand traits yet but a explanation would be nice
struct Person;
trait Speaks {
fn speak(&self) {
println!("Yo yiggity yo")
}
}
impl Speaks for Person {}
impl Person {
fn say(&self) {
println!("Yo yiggity yo")
}
}
fn main() {
let john: Box<dyn Speaks> = Box::new(Person);
john.speak();
let carl: Person = Person;
carl.say();
}
>>>Yo yiggity yo
>>>Yo yiggity yo