π Traits & Generics
Defining Traits
Concept
A trait defines shared behavior in an abstract way. Traits are similar to interfaces in other languages, but with superpowers.
You define a trait with the trait keyword, then implement it for specific types with impl TraitName for Type.
example.rs
trait Greet {
fn hello(&self) -> String;
// Default implementation
fn goodbye(&self) -> String {
format!("Goodbye from {}", self.hello())
}
}
struct English;
struct Spanish;
impl Greet for English {
fn hello(&self) -> String {
String::from("Hello!")
}
}
impl Greet for Spanish {
fn hello(&self) -> String {
String::from("Β‘Hola!")
}
}Quick Check
What can a trait provide besides method signatures?
1 / 3