Rust Traits: Defining Interfaces, Default Methods, and Trait Bounds
Static dispatch versus dyn, associated types versus generic parameters, and the object-safety and orphan rules that decide what an API can express.

Quick Summary
A trait declares behavior: a set of method signatures that a type can implement. It plays the role of an interface, but with three properties interfaces usually lack — default method bodies, associated types and constants, and the ability to be used as a bound on generic code that is then monomorphised and inlined.
There are two ways to consume a trait, and choosing between them is the main design decision. A generic bound (fn f<T: Shape>(s: T) or impl Shape) is resolved at compile time: one copy of the function per concrete type, no vtable, no allocation, but larger binaries and no heterogeneous collections. A trait object (&dyn Shape, Box<dyn Shape>) is resolved at runtime through a vtable: one function, dynamic dispatch, and you can store different types in one Vec. Both are static dispatch when you use impl Trait; only dyn pays the indirection.
Two constraints surprise newcomers. Object safety (now called dyn compatibility) forbids generic methods and methods returning Self by value in a dyn context. And the orphan rule forbids implementing a foreign trait for a foreign type, which is why newtype wrappers exist.
Basic syntax and query signatures
trait Shape {
// Required method
fn area(&self) -> f64;
// Required associated const, with a default
const SIDES: u8 = 0;
// Provided method: can call the required ones
fn describe(&self) -> String {
format!("area={:.2}, sides={}", self.area(), Self::SIDES)
}
}
struct Circle { r: f64 }
struct Square { s: f64 }
impl Shape for Circle {
fn area(&self) -> f64 { std::f64::consts::PI * self.r * self.r }
const SIDES: u8 = 0;
}
impl Shape for Square {
fn area(&self) -> f64 { self.s * self.s }
const SIDES: u8 = 4;
fn describe(&self) -> String { format!("square {}", self.area()) } // override
}Generic bounds, where clauses, and impl Trait:
fn print_area<T: Shape>(s: &T) { println!("{}", s.area()); }
fn total_area(shapes: &[impl Shape]) -> f64 { // one concrete type per call
shapes.iter().map(|s| s.area()).sum()
}
fn largest<T>(items: &[T]) -> Option<&T>
where
T: PartialOrd + std::fmt::Debug,
{
items.iter().max_by(|a, b| a.partial_cmp(b).unwrap())
}
// Return position impl Trait: caller gets an opaque type
fn make_shape() -> impl Shape { Circle { r: 1.0 } }Trait objects for heterogeneity and stored behaviour:
let shapes: Vec<Box<dyn Shape>> = vec![
Box::new(Circle { r: 1.0 }),
Box::new(Square { s: 2.0 }),
];
fn render(shapes: &[Box<dyn Shape>]) -> f64 { shapes.iter().map(|s| s.area()).sum() }
// Trait objects with lifetime and auto-trait bounds
let handler: Box<dyn Fn(&str) -> String + Send + 'static> = Box::new(|s| s.to_uppercase());Associated types versus generic parameters:
trait Container {
type Item; // exactly one implementation per type
fn get(&self, i: usize) -> Option<&Self::Item>;
}
impl Container for Vec<String> {
type Item = String;
fn get(&self, i: usize) -> Option<&String> { self.as_slice().get(i) }
}
trait Convert<T> { // generic: many implementations possible
fn convert(&self) -> T;
}Key comparison table
| Form | Dispatch | Allocation | Heterogeneous collection | Binary size |
|---|---|---|---|---|
fn f<T: Trait>(x: T) | Static, monomorphised | None | No | Larger (one copy per type) |
fn f(x: impl Trait) | Static | None | No | Larger |
fn f(x: &dyn Trait) | Dynamic (vtable) | None for the reference | Yes | Smaller |
fn f(x: Box<dyn Trait>) | Dynamic | Yes (box) | Yes | Smaller |
fn f() -> impl Trait | Static, opaque | None | No (one hidden type) | Larger |
| Choice | Prefer when |
|---|---|
Generic parameter T: Trait | Hot path, no heterogeneity, API clarity |
impl Trait in argument | Same as generic, shorter signature |
impl Trait in return | Hiding a concrete iterator/closure type |
&dyn Trait | Plugin-style dispatch, borrowed heterogeneous list |
Box<dyn Trait> | Owned heterogeneous collection, trait stored in a struct |
| Dyn-compatibility rule | Blocks dyn when |
|---|---|
| No generic methods | fn f<T>(&self) |
No Self by value in return | fn clone_me(&self) -> Self |
| No associated constants without a value | const X: u8; |
where Self: Sized methods are excluded | Those methods become uncallable on dyn |
Practical edge cases and deep dives
1. Default methods are resolved on the static type
trait Greet { fn name(&self) -> String; fn greet(&self) { println!("hi {}", self.name()); } }
struct A;
impl Greet for A { fn name(&self) -> String { "A".into() } }
let a = A;
a.greet(); // prints "hi A"The default body is compiled once per implementing type, so self is dispatched statically inside it. That is also why a default method can call required methods that do not exist yet when the trait is written.
2. Associated types versus a generic parameter
Iterator uses type Item because a type should iterate over exactly one item type; From<T> uses a generic parameter because a type can be converted from many sources.
// Wrong shape: Item as a generic parameter breaks every iterator API
// trait BadIter<Item> { fn next(&mut self) -> Option<Item>; }
// Right shape: one item type per iterator, so `for` can infer it
trait GoodIter { type Item; fn next(&mut self) -> Option<Self::Item>; }The practical consequence: with an associated type, code writes I::Item and the compiler pins it; with a generic parameter, callers must name it at every use site and inference gets harder.
3. Object safety failures and the where Self: Sized escape
trait Store {
fn get(&self, key: &str) -> Option<String>;
fn put<T: serde::Serialize>(&self, key: &str, v: &T); // generic: not dyn compatible
}
// error[E0038]: the trait `Store` cannot be made into an object
let s: Box<dyn Store> = unimplemented!();Two fixes: move the generic method behind where Self: Sized (it then exists only for concrete types), or make the method take a trait object.
trait Store {
fn get(&self, key: &str) -> Option<String>;
fn put(&self, key: &str, v: &dyn erased_serde::Serialize)
where
Self: Sized;
}4. Blanket impls and coherence
trait Describe { fn describe(&self) -> String; }
impl<T: std::fmt::Display> Describe for T {
fn describe(&self) -> String { format!("{self}") }
}
// error[E0119]: conflicting implementations of trait `Describe` for type `MyType`
// impl Describe for MyType { ... }A blanket implementation claims every matching type forever, including types written later. Overlap is rejected at compile time; the workaround is a marker trait or a newtype, never a runtime check.
5. The orphan rule and the newtype wrapper
// error[E0117]: only traits defined in the current crate can be implemented
// for types defined outside of the crate
// impl std::fmt::Display for Vec<u8> { ... }
struct Hex(Vec<u8>); // local type: allowed
impl std::fmt::Display for Hex {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", self.0.iter().map(|b| format!("{b:02x}")).collect::<String>())
}
}The rule exists so that adding a trait or type in another crate cannot break your build. A newtype costs one field and gives you local implementation rights.
6. Supertraits and derived bounds
trait Animal: std::fmt::Debug + Clone {
fn name(&self) -> &str;
}
fn dump<T: Animal + Send>(a: &T) { println!("{:?}", a); } // Debug available via supertraitT: Animal implies T: Debug + Clone; you do not repeat those bounds. Without the supertrait, every generic function using Debug would need its own + Debug.
7. dyn in struct fields and the Send + Sync question
struct App {
store: Box<dyn Store + Send + Sync>,
on_event: Box<dyn Fn(&str) + Send + Sync>,
}A trait object has no auto traits by default; Box<dyn Store> is neither Send nor Sync, so a struct holding one cannot move across threads. Adding + Send + Sync is required, and the implementing types must satisfy them. This is the single most common reason a service that compiles fails to satisfy an async runtime's Send requirement.
Common mistakes and runtime errors
| Error | Cause | Fix |
|---|---|---|
E0277 trait bound not satisfied | Missing impl or bound | Implement, or add the bound |
E0046 not all trait items implemented | Missing required method/const | Add the item |
E0038 cannot be made into an object | Generic method or Self return | where Self: Sized, or redesign |
E0119 conflicting implementations | Blanket impl overlap | Marker trait or newtype |
E0117 only traits defined in current crate | Orphan rule | Newtype wrapper |
dyn Trait not Send | Auto traits not implied | Add + Send + Sync |
expected dyn Trait, found &T | Missing dyn keyword | &dyn Trait |
impl Trait not allowed in struct field | Opaque types only in fn signatures | Use Box<dyn Trait> or a generic parameter |
Method not found on dyn Trait | Method has where Self: Sized | Call it on the concrete type |
| Unreasonably large generic function | Monomorphisation per type | Accept &dyn Trait at the outer boundary |
| Ambiguous method call | Two traits with the same method | Fully qualified <T as Trait>::method(&x) |
Try matching browser tools
All toolsSmall utilities that fit Rust work — they run entirely in this browser tab, so nothing you paste leaves your device.
Related Rust guides
All Rust guidesRust Unsafe: Raw Pointers, FFI Bindings, and Soundness Invariants
What unsafe actually unlocks, the five soundness contracts behind raw pointers, and the FFI rules for repr(C), CString and unwinding.
Rust Pin and Unpin: Memory Pinning, Self-Referential Structs, and Futures
Why a future must not move after polling starts, what Unpin opts out of, and how Box::pin, pin! and map_unchecked_mut express that guarantee.
Rust Arrays and Slices: Fixed Arrays, &[T] Fat Pointers, and DSTs
An array carries its length in its type; a slice carries it in the pointer. The split_at_mut, chunks and TryFrom patterns that follow from that.
Rust Macros: macro_rules! Patterns, Hygiene, and Procedural Macros
Matcher fragments, repetition, hygiene and the proc-macro crate. How to read a macro_rules! error and when a derive macro is the right tool.
More in Rust
All Rust guidesThe guides filed next to this one in Rust, in library order.