Traits in Rust define shared behavior that multiple types can implement to enable polymorphism and code reuse. You define a trait with the trait keyword, list method signatures, and then implement it for specific types using impl TraitName for Type.
trait Summary {
fn summarize(&self) -> String;
}
struct NewsArticle {
headline: String,
}
impl Summary for NewsArticle {
fn summarize(&self) -> String {
format!("{}...", self.headline)
}
}
This allows you to call summarize() on any type that implements the Summary trait, regardless of the underlying data structure.