Traits Basics
8 examples to get you started with traits - 5 basic and 3 intermediate.
Prerequisites
Basic Examples
1. Define and Implement a Trait
trait Greet {
fn greet(&self) -> String;
}
struct Person { name: String }
impl Greet for Person {
fn greet(&self) -> String {
format!("Hello, {}!", self.name)
}
}
fn main() {
let p = Person { name: "Ada".into() };
println!("{}", p.greet());
}- Traits define shared behavior
impl Trait for Typeprovides implementation- Traits can have multiple methods
- Orphan rule: impl must be in crate of trait or type
2. Default Method Bodies
trait Log {
fn level(&self) -> &'static str { "info" }
fn msg(&self) -> &str;
}
struct Event(&'static str);
impl Log for Event {
fn msg(&self) -> &str { self.0 }
}- Trait methods can have defaults
- Implementors override selectively
- Default methods can call other trait methods
- See Default Methods page
3. Trait Bounds on Functions
use std::fmt::Display;
fn print_twice<T: Display>(value: T) {
println!("{value} {value}");
}
fn main() {
print_twice(42);
}T: Displayconstrains generic parameter- Bounds enable calling trait methods on
T - Multiple bounds with
+ - Compiler monomorphizes generics
4. impl Trait in Parameters
use std::fmt::Display;
fn show(value: impl Display) {
println!("{value}");
}- Syntax sugar for single trait bound
impl Display~=T: Displayanonymous- Cleaner signatures for simple cases
+for multiple:impl Display + Clone
5. Return impl Trait
fn make_greeting() -> impl std::fmt::Display {
"hello"
}
fn main() {
println!("{}", make_greeting());
}- Hides concrete return type
- Caller only uses trait interface
- Single concrete type per function body required
- Different from
dyn Traittrait objects
Intermediate Examples
6. Trait Objects dyn Trait
trait Drawable { fn draw(&self); }
struct Circle;
impl Drawable for Circle { fn draw(&self) { println!("circle"); } }
fn render(shape: &dyn Drawable) {
shape.draw();
}
fn main() {
render(&Circle);
}- Runtime dispatch via vtable
- Heterogeneous collection of types
- Object safety rules apply
- See Trait Objects page
7. Supertraits
trait Outline: std::fmt::Display {
fn outline(&self) -> String;
}Outline: DisplayrequiresDisplayfirst- Bounds chain behavior
impl Outlinemust also implDisplay- See Supertraits page
8. Associated Types Preview
trait Iter {
type Item;
fn next(&mut self) -> Option<Self::Item>;
}- Associated type names output element type
- One impl per type (unlike generic method params)
Iterator::Itemis canonical example- See Associated Types page
Related: Traits & Generics Best Practices
Stack versions: This page was written for Rust 1.97.0 (edition 2024), Tokio 1.x, Axum 0.8, serde 1.0, sqlx 0.8, clap 4, and Polars 0.46+.