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