Traits and Generics
Traits
Shared Behavior
A trait defines methods a type can implement. Implementing the trait gives the type that behavior.
Program
Play the program to implement a Greet trait for a struct.
traits.rs
trait Greet {
fn hello(&self) -> String;
}
struct Person {
name: String,
}
impl Greet for Person {
fn hello(&self) -> String {
format!("Hi, {}", self.name)
}
}
fn main() {
let p = Person { name: String::from("Ada") };
let msg = p.hello();
println!("{msg}");
}
trait
`trait Greet` declares required methods.
impl Trait for Type
`impl Greet for Person` provides the behavior.
method call
`p.hello()` runs the implemented method.