Define a trait using the `trait` keyword and implement it for a type using `impl TraitName for Type` to share behavior across different structs.
Define a trait with the trait keyword to declare shared behavior, then use impl TraitName for Type to provide the concrete logic for a specific type.
trait Message {
fn call(&self);
}
struct MyMessage;
impl Message for MyMessage {
fn call(&self) {
println!("Message sent");
}
}
fn main() {
let m = MyMessage;
m.call();
}
A trait is like a contract that defines a set of rules (methods) that different types must follow to be considered compatible. You define the contract once, and then any type can choose to sign it by implementing those specific rules. This lets you write code that works with many different types as long as they all agree to follow the same contract.