What Are Traits in Rust and How Do They Work?

Traits in Rust define shared behavior for types, enabling polymorphism and code reuse through method signatures and implementations.

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.