Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

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.

~4 min readRust
#Rust#Traits#OOP
3D illustration of a shared behavior blueprint plugged into several struct shapes through generic bound sockets

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

rust
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:

rust
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:

rust
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:

rust
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

FormDispatchAllocationHeterogeneous collectionBinary size
fn f<T: Trait>(x: T)Static, monomorphisedNoneNoLarger (one copy per type)
fn f(x: impl Trait)StaticNoneNoLarger
fn f(x: &dyn Trait)Dynamic (vtable)None for the referenceYesSmaller
fn f(x: Box<dyn Trait>)DynamicYes (box)YesSmaller
fn f() -> impl TraitStatic, opaqueNoneNo (one hidden type)Larger
ChoicePrefer when
Generic parameter T: TraitHot path, no heterogeneity, API clarity
impl Trait in argumentSame as generic, shorter signature
impl Trait in returnHiding a concrete iterator/closure type
&dyn TraitPlugin-style dispatch, borrowed heterogeneous list
Box<dyn Trait>Owned heterogeneous collection, trait stored in a struct
Dyn-compatibility ruleBlocks dyn when
No generic methodsfn f<T>(&self)
No Self by value in returnfn clone_me(&self) -> Self
No associated constants without a valueconst X: u8;
where Self: Sized methods are excludedThose methods become uncallable on dyn

Practical edge cases and deep dives

1. Default methods are resolved on the static type

rust
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.

rust
// 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

rust
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.

rust
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

rust
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

rust
// 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

rust
trait Animal: std::fmt::Debug + Clone { fn name(&self) -> &str; } fn dump<T: Animal + Send>(a: &T) { println!("{:?}", a); } // Debug available via supertrait

T: 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

rust
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

ErrorCauseFix
E0277 trait bound not satisfiedMissing impl or boundImplement, or add the bound
E0046 not all trait items implementedMissing required method/constAdd the item
E0038 cannot be made into an objectGeneric method or Self returnwhere Self: Sized, or redesign
E0119 conflicting implementationsBlanket impl overlapMarker trait or newtype
E0117 only traits defined in current crateOrphan ruleNewtype wrapper
dyn Trait not SendAuto traits not impliedAdd + Send + Sync
expected dyn Trait, found &TMissing dyn keyword&dyn Trait
impl Trait not allowed in struct fieldOpaque types only in fn signaturesUse Box<dyn Trait> or a generic parameter
Method not found on dyn TraitMethod has where Self: SizedCall it on the concrete type
Unreasonably large generic functionMonomorphisation per typeAccept &dyn Trait at the outer boundary
Ambiguous method callTwo traits with the same methodFully qualified <T as Trait>::method(&x)

Try matching browser tools

All tools

Small utilities that fit Rust work — they run entirely in this browser tab, so nothing you paste leaves your device.

All Rust guides

More in Rust

All Rust guides

The guides filed next to this one in Rust, in library order.