Learn more: The Rust Reference, The Book, Rust by Example, Rust Design Patterns

In Rust, a trait is a way to define shared behavior that can be implemented by multiple types. Traits are similar to interfaces in other languages but with some unique features specific to Rust. Here’s a high-level overview of traits in Rust:

Here’s a simple example of a trait in Rust:

trait Summary {
    fn summarize(&self) -> String;
}

struct NewsArticle {
    headline: String,
    location: String,
    author: String,
    content: String,
}

impl Summary for NewsArticle {
    fn summarize(&self) -> String {
        format!("{}, by {} ({})", self.headline, self.author, self.location)
    }
}

struct Tweet {
    username: String,
    content: String,
}

impl Summary for Tweet {
    fn summarize(&self) -> String {
        format!("{}: {}", self.username, self.content)
    }
}