Defining & Implementing Traits in Rust

From the Rust cheat sheet ยท Traits ยท verified Jul 2026

Defining & Implementing Traits

Create traits, implement them for types, and use trait bounds.

rust
// Define a trait
trait Summary {
    fn summarize(&self) -> String;

    // Default implementation
    fn preview(&self) -> String {
        format!("{}...", &self.summarize()[..20])
    }
}

// Implement for a type
impl Summary for Article {
    fn summarize(&self) -> String {
        format!("{} by {}", self.title, self.author)
    }
}
๐Ÿ’ก impl Trait in parameters = static dispatch (monomorphized); dyn Trait = dynamic dispatch (vtable)
โšก Use where clauses when trait bounds get complex โ€” much more readable than inline bounds
๐Ÿ“Œ Trait objects (Box<dyn Trait>) let you store different types in one collection
๐ŸŸข impl Trait in return position means "returns some type implementing Trait" โ€” great for closures
traitsboundsdynimpl-trait

More Rust tasks

Back to the full Rust cheat sheet