Traits: Contracts Without Inheritance
local graph
Chapter 4 — Traits: Contracts Without Inheritance
Section titled “Chapter 4 — Traits: Contracts Without Inheritance”Pacta sunt servanda. (Agreements must be kept.)
Structs and enums model data. Impl blocks attach behavior. But a diagram in the previous discussion hinted at something more: multiple impl blocks can attach different behaviors to the same struct, including blocks that mention Display and Debug. These are traits, Rust’s mechanism for defining shared behavior across types.
Object-oriented developers recognize the concept immediately. An interface in Java or C# declares methods that implementing classes must provide. Traits serve a similar purpose, defining a set of method signatures that types can implement. Yet traits diverge from interfaces in significant ways. Traits can provide default implementations. Traits can be implemented for types you did not define. Traits can express complex relationships between types through associated types. And traits, combined with generics, enable a form of polymorphism that resolves at compile time with no runtime overhead.
Defining behavior contracts
A trait defines a contract: a set of method signatures that any implementing type must provide. The simplest traits contain only method signatures with no implementation. A Summary trait might require a summarize method that returns a String. Any type implementing Summary must provide this method. The trait says nothing about how summarization works; it only requires that the capability exists.
Implementing a trait for a type uses the impl TraitName for TypeName syntax, followed by implementations of all required methods:
pub trait Summary { fn summarize(&self) -> String;}
pub struct NewsArticle { pub headline: String, pub author: String, pub content: String,}
impl Summary for NewsArticle { fn summarize(&self) -> String { format!("{} by {}", self.headline, self.author) }}
pub struct Tweet { pub username: String, pub content: String,}
impl Summary for Tweet { fn summarize(&self) -> String { format!("{}: {}", self.username, self.content) }}A NewsArticle implements Summary by returning the headline and author. A Tweet implements it by returning the username and text. Each type provides its own implementation; the trait merely ensures the method exists and has the correct signature.
This resembles interface implementation in object-oriented languages, but the syntax reveals a key difference. The implementation is separate
[!missing-source] Printed pages 132–133 are absent from the scan (skipped between PDF 133 and PDF 134). The text breaks off mid-sentence above (“The implementation is separate …”) and resumes mid-discussion below; the missing content cannot be reconstructed.
A method that takes self consumes the value entirely. Calling it requires ownership, and the original value is no longer usable afterward. Traits with self-by-value methods are therefore more restrictive: callers must own the value, not just borrow it. Choosing between &self, &mut self, and self is a fundamental part of a trait’s API design, as it directly shapes how implementations and callers interact.
Within a trait definition, the identifier Self (capital S) refers to the concrete type that will implement the trait. It acts as a placeholder for “the implementing type.”
This becomes especially useful for methods that return Self. For example, if a Clone-like trait defines a method returning Self, each implementation returns its own type. Cloning a String produces a String, cloning a Vec<T> produces a Vec<T>, and so on. The trait itself remains generic and abstract, while each implementation substitutes its concrete type for Self. This is how traits can describe behavior without knowing the exact type in advance.
Traits can also define associated functions, which are functions without a self parameter. These are not called on an instance but on the type itself. They are commonly used for constructors or factory-style APIs.
A canonical example is the Default trait in the standard library, which defines a default function returning Self. Any type that implements Default provides a way to construct a “default” instance of itself. When you call Default::default(), the compiler uses type inference to determine which concrete type is expected and returns a default value of that type. This allows generic code to create values without hard-coding concrete constructors.
Default implementations
Traits can provide default implementations for some or all of their methods. A method with a default implementation does not require implementors to provide their own; they can accept the default or override it. This pattern enables traits to provide both required methods (the core contract) and convenience methods (built on the required methods).
Consider a Summary trait with a required summarize_author method and a summarize method with a default implementation:
pub trait Summary { fn summarize_author(&self) -> String;
fn summarize(&self) -> String { format!("(Read more from {}...)", self.summarize_author()) }}
impl Summary for Tweet { fn summarize_author(&self) -> String { format!("@{}", self.username) } // Uses default summarize}
impl Summary for NewsArticle { fn summarize_author(&self) -> String { self.author.clone() }
fn summarize(&self) -> String { format!("{}, by {}", self.headline, self.author) }}The default implementation formats the author with boilerplate text. Types implementing Summary must provide summarize_author, but they can use the default summarize or override it. NewsArticle overrides summarize to include the headline, while Tweet accepts the default.
Default implementations can call other trait methods, including required methods that have no default. The default summarize can call self.summarize_author() even though summarize_author has no implementation in the trait itself. Each implementing type provides summarize_author, and the default summarize uses that implementation. This resembles the template method pattern from object-oriented design, where a base class defines an algorithm skeleton with some steps delegated to subclasses. Traits achieve this without inheritance: the default implementation provides the skeleton, and required methods provide the customization points.
The distinction between required and default methods guides trait design. Required methods capture the essential behavior that varies between implementations. Default methods provide common functionality built on those essential behaviors. A well-designed trait minimizes required methods while maximizing what can be expressed as defaults, reducing the burden on implementors without limiting flexibility.
This pattern appears throughout the standard library. The Iterator trait requires only a next method, returning the next item or None. From this single method, the trait provides dozens of default methods: map, filter, fold, count, last, nth, and many more. Implementing Iterator for a custom type requires only next; all other methods work automatically. Custom types can override specific default methods for efficiency (a custom count might track size directly rather than iterating), but the defaults provide correct behavior without additional effort.
The following diagram illustrates how default implementations reduce implementor burden:
graph TD
subgraph TI["trait Iterator"]
N["fn next(&mut self) -> Option#lt;Item#gt;"]
M["fn map (default)"]
F["fn filter (default)"]
FO["fn fold (default)"]
C["fn count (default)"]
end
subgraph IM["impl Iterator for MyType"]
NR["fn next (required)"]
CO["fn count (optional override)"]
end
N --> NR
C -- override --> CO
[!visual-conversion] Default implementations reduce what each type must implement. Print diagram (PDF 137, printed p. 137) recreated in Mermaid; labels verbatim.
Trait bounds and where clauses
Traits become truly powerful when combined with generics. A generic function can accept any type, but often you need to constrain which types are acceptable. Trait bounds specify that a generic type must implement certain traits, enabling the function to use those trait methods on the generic type.
The syntax places bounds after a colon in the generic type declaration:
pub fn notify<T: Summary>(item: &T) { println!("Breaking news: {}", item.summarize());}The function taking T: Summary can call summarize on values of type T because the bound guarantees that T implements Summary. Without the bound, the compiler rejects the call: it cannot know whether an arbitrary T has a summarize method.
Multiple bounds combine with the plus sign. A type constrained by T: Summary + Clone must implement both traits:
pub fn notify_and_copy<T: Summary + Clone>(item: &T) -> T { println!("Breaking news: {}", item.summarize()); item.clone()}When bounds become complex, where clauses provide clearer syntax. Rather than cramming bounds into the generic parameter list, a where clause follows the function signature and lists constraints separately:
fn some_function<T, U>(t: &T, u: &U) -> i32where T: Summary + Clone, U: Clone + Debug,{ // implementation}This improves readability for functions with several generic parameters. The meaning is identical; where clauses are purely a syntactic convenience for managing complexity.
Trait bounds enable generic code that is both flexible and safe. The function works with any type meeting the bounds, allowing callers to use it with their own types. The compiler verifies that the bounds are satisfied at each call site, catching type errors at compile time. And because the concrete type is known at compile time, the compiler generates specialized code for each concrete type used, eliminating the overhead of virtual dispatch.
This last point deserves emphasis. In Java or C#, calling an interface method involves indirection: the runtime looks up the concrete type and dispatches to the appropriate implementation. This overhead is small but present on every call. Rust’s generics with trait bounds pay this cost at compile time. The compiler generates a specialized version of the generic function for each concrete type, with direct calls to the concrete method implementations. The resulting code runs as fast as if you had written separate functions for each type.
The trade-off is binary size: each specialization adds code to the final binary. For most applications, this trade-off favors the generic approach. The same code handles multiple types without runtime dispatch overhead, and the compiler optimizes each specialization independently. When binary size matters (embedded systems, WebAssembly), this trade-off requires more consideration.
Returning types that implement traits
Functions can return values of types that implement specific traits without naming the concrete type. The impl Trait syntax in return position tells the compiler that the function returns some type implementing the trait, but callers do not know (and cannot depend on) which specific type.
This feature enables returning closures and iterators, whose concrete
types are complex and unnameable. A function that returns a filtered,
mapped iterator over a collection would have a return type with
deeply nested generics reflecting the chain of operations. With impl
Iterator<Item = i32>, the function expresses that it returns
something you can iterate over to get i32 values, hiding the complexity
of the concrete type.
The limitation is that impl Trait in return position represents a single concrete type, not a choice of types. A function cannot return either TypeA or TypeB as impl Trait based on runtime conditions, because the concrete type must be known at compile time. For truly dynamic dispatch (returning different types based on runtime logic), trait objects are necessary.
When traits diverge from interfaces
Despite surface similarities, traits differ from object-oriented interfaces in ways that become significant as designs grow. Understanding these differences helps object-oriented developers leverage traits effectively rather than forcing them into interface-shaped patterns.
Associated types
Traits can define associated types: type placeholders that implementations fill in. The Iterator trait has an associated type Item representing the type of values produced. Each implementation specifies its Item: an iterator over a vector of strings has Item = String. The associated type becomes part of the trait’s contract, appearing in method signatures as Self::Item.
Associated types differ from generic parameters on traits. A trait like
Iterator<T> with a generic parameter could be implemented
multiple times for the same type with different T values. A type could
be both Iterator<i32> and Iterator<String>. With associated
types, each type has exactly one Iterator implementation with one Item
type. The choice between generic parameters and associated types
reflects whether multiple implementations make sense.
Consider a graph traversal trait with an associated type for the node type:
pub trait Graph { type Node; type Edge;
fn nodes(&self) -> Vec<Self::Node>; fn edges(&self) -> Vec<Self::Edge>; fn neighbors(&self, node: &Self::Node) -> Vec<Self::Node>;}pub struct AdjacencyList { adjacencies: Vec<Vec<usize>>,}
impl Graph for AdjacencyList { type Node = usize; type Edge = (usize, usize);
fn nodes(&self) -> Vec<Self::Node> { (0..self.adjacencies.len()).collect() }
fn edges(&self) -> Vec<Self::Edge> { let mut edges = Vec::new(); for (from, neighbors) in self.adjacencies.iter().enumerate() { for &to in neighbors { edges.push((from, to)); } } edges }
fn neighbors(&self, node: &Self::Node) -> Vec<Self::Node> { self.adjacencies[*node].clone() }}
pub struct NamedGraph { nodes: Vec<String>, edges: Vec<(String, String)>,}
impl Graph for NamedGraph { type Node = String; type Edge = (String, String);
fn nodes(&self) -> Vec<Self::Node> { self.nodes.clone() } fn edges(&self) -> Vec<Self::Edge> { self.edges.clone() }
fn neighbors(&self, node: &Self::Node) -> Vec<Self::Node> { self.edges.iter() .filter(|(from, _)| from == node) .map(|(_, to)| to.clone()) .collect() }}Each Graph implementation specifies its own Node and Edge types.
Functions working with graphs use G::Node and G::Edge to refer to
these types generically.
In my experience, associated types suit traits where each implementation has a natural, unique type relationship. Iterators produce one type of item. Conversion traits have one input or output type. Generic parameters suit traits where multiple implementations for the same type are meaningful, like arithmetic operations between different numeric types.
Associated constants
Traits can also define associated constants: values that each implementation must provide or that have defaults which implementations can override. Where associated types let traits require implementors to specify a type, associated constants let traits require implementors to specify a value. The constant becomes part of the trait’s contract, accessible through the implementing type as Type::CONSTANT_NAME.
This feature addresses a common need in interface design: specifying invariant values that differ between implementations but remain fixed for each implementation. A buffer trait might define a maximum size. A protocol handler might specify a version number. A mathematical type might declare precision bounds. In object-oriented languages, these values typically become abstract methods that return constants, adding runtime overhead for what is conceptually compile-time information.
Consider a trait for types that have a notion of identity or zero value:
pub trait Identity { const ZERO: Self; const ONE: Self;
fn is_zero(&self) -> bool;}
impl Identity for i32 { const ZERO: Self = 0; const ONE: Self = 1;
fn is_zero(&self) -> bool { *self == Self::ZERO }}
impl Identity for f64 { const ZERO: Self = 0.0; const ONE: Self = 1.0;
fn is_zero(&self) -> bool { *self == Self::ZERO }}Each implementation provides its own ZERO and ONE values appropriate to its type. Code generic over the Identity trait can use these constants without knowing the concrete type. A matrix library might initialize elements to T::ZERO. A numeric algorithm might use T::ONE as a multiplicative identity. The constants are resolved at compile time, incurring no runtime cost.
Associated constants can have default values that implementations may override. This pattern works well for configuration values where most implementations share a common default but some require different settings:
pub trait Buffer { const MAX_SIZE: usize = 4096; const GROW_FACTOR: usize = 2;
fn capacity(&self) -> usize; fn grow(&mut self);}Implementations that need the default behavior simply omit the constant definitions. Implementations with special requirements override only the constants they need to change. This is more elegant than requiring every implementation to repeat common values or forcing implementations to delegate to default method implementations that query constants.
The combination of associated types and associated constants creates expressive trait definitions. A trait might define both a type for items and a constant for maximum count:
pub trait Container { type Item; const MAX_ITEMS: usize;
fn items(&self) -> &[Self::Item]; fn add(&mut self, item: Self::Item) -> Result<(), &'static str>;}This declares that any Container has a specific item type and a specific capacity limit, both determined by the implementation. The trait captures the full contract: what types flow through the container and what constraints govern its behavior. Generic code can rely on both the type relationships and the constant values, all verified at compile time.
Coherence and the orphan rule
The orphan rule mentioned earlier has deeper implications than preventing conflicting implementations. It shapes how traits and types are organized across crates. Library authors must consider whether their traits should be implemented by downstream users (making the trait public but types less constrained) or reserved for types within the library (using sealed trait patterns).
This coherence system prevents the fragile base class problem that plagues inheritance hierarchies. Adding a method to a base class in Java or C# can break subclasses that happen to have methods with the same signature. Adding a method to a trait in Rust cannot break existing implementations because trait implementations are explicit and separate. New methods with default implementations extend the trait without requiring changes to existing implementors.
Object safety and trait objects
Traits can be used in two ways: as bounds on generic types (static dispatch) or as trait objects (dynamic dispatch). Not all traits can be used as trait objects; those that can are called object-safe.
A trait is object-safe if its methods can be called through a pointer without knowing the concrete type. Methods that return Self prevent object safety because the concrete return type varies per implementation. Methods with generic type parameters prevent object safety because the compiler cannot know which monomorphizations to include in the vtable. Methods that take self by value can prevent object safety in complex cases.
The following traits demonstrate what prevents object safety:
// These traits are NOT object-safe
// 1. Method returns Self - concrete type unknown at runtimetrait Clonable { fn duplicate(&self) -> Self;}// Cannot use: dyn Clonable - what type does duplicate() return?
// 2. Method has generic parameter - infinite possible monomorphizationstrait Processor { fn process<T>(&self, item: T);}// Cannot use: dyn Processor - which process::<T> goes in the vtable?
// 3. Associated function without self - no instance to dispatch ontrait Factory { fn create() -> Self;}// Cannot use: dyn Factory - create() has no self parameterEach violation has workarounds that preserve object safety while providing similar functionality:
// Object-safe alternatives
// Instead of returning Self, return a boxed trait objecttrait ClonableBoxed { fn duplicate(&self) -> Box<dyn ClonableBoxed>;}
// Instead of generic parameter, use trait object parametertrait ProcessorDyn { fn process_any(&self, item: &dyn std::any::Any);}// Instead of associated function, use method taking &selftrait FactoryDyn { fn create_another(&self) -> Box<dyn FactoryDyn>;}These patterns trade some flexibility for the ability to use dynamic dispatch. The boxed return types allow heterogeneous collections and runtime polymorphism.
When a trait is object-safe, you can create trait objects using dyn Trait syntax:
pub fn notify_dynamic(item: &dyn Summary) { println!("Breaking news: {}", item.summarize());}
fn main() { let article = NewsArticle { /* ... */ }; let tweet = Tweet { /* ... */ };
notify_dynamic(&article); notify_dynamic(&tweet);}A function taking &dyn Summary accepts a reference to any type implementing Summary, with the concrete type unknown at compile time. The runtime representation includes a pointer to the value and a pointer to a vtable containing the trait method implementations for that concrete type.
Trait objects enable heterogeneous collections: a Vec<Box<dyn Summary>> can contain a mix of NewsArticle and Tweet values:
let items: Vec<Box<dyn Summary>> = vec![ Box::new(NewsArticle { /* ... */ }), Box::new(Tweet { /* ... */ }),];
for item in &items { println!("{}", item.summarize());}Generics cannot achieve this because a Vec<T> holds values of a single concrete type T. The trade-off is runtime dispatch overhead and loss of type information (you cannot recover the concrete type from a trait object without additional mechanisms like downcasting).
The following diagram contrasts static and dynamic dispatch:
graph LR
subgraph SD["Static Dispatch"]
S1["fn notify#lt;T: Summary#gt;(item: &T)"] --> S2["Compiler generates specialized code"] --> S3["Direct function calls, no overhead"]
end
subgraph DD["Dynamic Dispatch"]
D1["fn notify(item: &dyn Summary)"] --> D2["Runtime vtable lookup"] --> D3["Indirection on each call"]
end
[!visual-conversion] Static dispatch eliminates overhead; dynamic dispatch enables heterogeneous collections. Print diagram (PDF 148, printed p. 148) recreated in Mermaid; labels verbatim.
Supertraits
Traits can require other traits as prerequisites. A trait with a supertrait bound requires implementing types to also implement the supertrait. A trait OutlinePrint: Display requires implementors to implement Display before they can implement OutlinePrint. Methods in OutlinePrint can use Display methods on self, knowing the bound is satisfied.
use std::fmt::{Display, Formatter, Result};
pub trait OutlinePrint: Display { fn outline_print(&self) { let output = self.to_string(); let len = output.len(); println!("{}","*".repeat(len + 4)); println!("* {} *", output); println!("{}","*".repeat(len + 4)); }}
pub struct Point { x: i32, y: i32,}
impl Display for Point { fn fmt(&self, f: &mut Formatter<'_>) -> Result { write!(f, "({}, {})", self.x, self.y) }}
impl OutlinePrint for Point {}
// Usage:// let p = Point { x: 1, y: 3 };// p.outline_print();// Outputs:// **********// * (1, 3) *// **********This is not inheritance. OutlinePrint does not inherit Display’s methods; it requires them as a dependency. The distinction matters: you cannot call Display methods on an OutlinePrint trait object unless the trait object also bounds on Display. Supertraits express capability dependencies, not hierarchical relationships.
The pattern is useful when traits build on other traits’ capabilities:
use std::fmt::Debug;
pub trait Serialize: Clone + Debug { fn serialize(&self) -> Vec<u8>;}
pub trait Comparable: PartialEq + PartialOrd { fn compare(&self, other: &Self) -> std::cmp::Ordering { self.partial_cmp(other).unwrap_or(std::cmp::Ordering::Equal) }}
#[derive(Clone, Debug, PartialEq, PartialOrd)]pub struct Record { id: u64, data: String,}
impl Serialize for Record { fn serialize(&self) -> Vec<u8> { format!("{}:{}", self.id, self.data).into_bytes() }}
impl Comparable for Record {}A serialization trait might require Debug for error reporting. A comparison trait might require equality. The supertrait bound documents and enforces these dependencies.
Essential standard library traits
The Rust standard library defines traits that establish conventions across the ecosystem. These traits are so fundamental that most types implement several of them, and generic code routinely requires them as bounds. Understanding these traits is essential because they appear constantly in real Rust code, both as bounds on generic functions and as capabilities you implement for your own types.
Many of these traits can be derived automatically using the #[derive(…)] attribute. The compiler generates standard implementations based on your type’s structure, applying the trait to each field recursively. Derived implementations work correctly for most cases, though you can always provide custom implementations when the generated behavior does not match your needs.
Clone and Copy
These two traits govern how values are duplicated. Clone provides explicit duplication through a clone() method, while Copy marks types that can be duplicated implicitly through simple bit-copying. The distinction reflects a fundamental difference in how types behave when assigned or passed to functions.
Copy is a marker trait with no methods. It signals that a type’s values are fully represented by their bits in memory, with no additional resources like heap allocations or file handles. Integers, floating-point numbers, booleans, and tuples of Copy types are all Copy. When a Copy type is assigned to a new variable or passed to a function, the bits are copied and both the original and the copy remain valid. This is the behavior familiar from primitive types in most languages.
Clone is more general. Any type can implement Clone, even types that manage external resources. The clone method performs whatever duplication is appropriate: for a String, it allocates new heap memory and copies the characters; for an Rc, it increments the reference count. Clone is explicit because duplication might be expensive or have semantic implications. A database connection wrapper’s clone might open a new connection or share the existing one, and the programmer should know which.
The relationship between these traits is hierarchical: every Copy type must also be Clone (the clone implementation just copies the bits), but not every Clone type is Copy. String is Clone but not Copy because cloning requires heap allocation. Types containing non-Copy fields cannot be Copy.
#[derive(Clone, Copy)]pub struct Point { x: f64, y: f64,}
#[derive(Clone)]pub struct Path { points: Vec<Point>, // Vec is not Copy, so Path cannot be Copy}For types that are cheap to copy and have no external resources, implementing Copy improves ergonomics by eliminating explicit clone calls. For types where duplication is expensive or semantically significant, implementing only Clone forces callers to acknowledge the cost. The choice between Clone-only and Clone+Copy is a design decision about how your type should be used.
Default
The Default trait provides a standard way to create a type’s default value. It has a single method, default(), that returns an instance of the type. This trait appears frequently as a bound in generic code that needs to construct values without knowing the concrete type.
For many types, the default value is obvious: zero for numbers, empty for collections, None for Option. The derive macro generates implementations that call Default on each field, producing a struct where every field has its default value. This works well for configuration structs, builders, and types where a sensible baseline exists.
#[derive(Default)]pub struct Config { timeout_seconds: u64, // defaults to 0 max_retries: u32, // defaults to 0 verbose: bool, // defaults to false endpoint: String, // defaults to ""}Custom Default implementations allow specifying more meaningful defaults than the zero values the derive macro produces. A configuration type might default to reasonable production settings. A buffer might default to a standard capacity. The implementation expresses what “default” means for your type’s domain.
Default also enables the struct update syntax with ..Default::default(). This pattern creates a struct with some fields specified and the rest defaulted, reducing boilerplate when only a few fields need non-default values. Generic functions bounded on Default can create placeholder values, initialize arrays, or provide fallbacks when other values are unavailable.
Debug and Display
These traits control how values are formatted as text. Debug is intended for programmer-facing output: error messages, logs, and debugging sessions. Display is intended for user-facing output: messages shown to end users, formatted reports, and string conversions. The distinction guides how much detail to include and what format to use.
Debug implementations should be unambiguous and complete enough to identify the value during debugging. The derive macro generates Debug implementations that print the type name and all field names and values, using a format that looks like Rust syntax. This is almost always appropriate for Debug; custom implementations are rarely needed except for types containing sensitive data that should not appear in logs.
#[derive(Debug)]pub struct User { id: u64, username: String, // Note: password_hash deliberately excluded from derived Debug}Display has no derive macro because there is no single correct format for user-facing output. A User might display as just the username, or as a formatted string like “User #123 (alice)”, depending on context. Implementing Display requires deciding what representation makes sense for users of your type.
Display is required for types to work with the {} format specifier and for implicit conversion to String via the to_string() method provided by the ToString trait (which is automatically implemented for any type implementing Display). Debug uses the {:?} and {:#?} format specifiers, with the latter producing pretty-printed multi-line output.
The standard practice is to derive Debug for nearly every type (enabling debugging and logging) and implement Display only for types that have a meaningful user-facing representation. Types that are internal implementation details often have Debug but not Display.
Comparison: PartialEq, Eq, PartialOrd, Ord
These four traits form a hierarchy governing equality and ordering comparisons. Understanding why there are four traits rather than two requires understanding that not all types have total equality or total ordering.
PartialEq defines the == and != operators. The “Partial” prefix indicates that equality might not be defined for all pairs of values. The canonical example is floating-point NaN (Not a Number): by IEEE 754 rules, NaN is not equal to anything, including itself. PartialEq allows this behavior; a type implementing PartialEq can have a == a return false for some values.
Eq is a marker trait extending PartialEq that promises reflexivity: every value equals itself. Integers, strings, and most types implement Eq. Floating-point types do not because of NaN. Types implementing Eq can be used as keys in HashMap and HashSet, which require that values equal themselves for correct behavior.
PartialOrd defines the comparison operators (<, >, <=, >=) and a partial_cmp method returning Option<Ordering>. The Option allows returning None when two values are not comparable. Floating-point types use this: NaN is not less than, equal to, or greater than any value, so comparisons involving NaN return None.
Ord extends PartialOrd with total ordering: every pair of values must be comparable, and partial_cmp never returns None. Ord is required for sorting operations and for keys in BTreeMap and BTreeSet. Types implementing Ord can always answer which of two values is smaller.
#[derive(PartialEq, Eq, PartialOrd, Ord)]pub struct Version { major: u32, minor: u32, patch: u32,}The derive macro implements these traits by comparing fields in declaration order, which works correctly for types like Version where field order matches comparison priority. For types where derived comparison is not appropriate, you must implement the traits manually, being careful to maintain the mathematical properties each trait promises: symmetry and transitivity for equality, antisymmetry and transitivity for ordering.
These traits interact with each other and with Hash (for hash-based collections). A type that implements Eq should implement Hash such that equal values hash to equal values. A type that implements Ord should have its Eq implementation consistent with its Ord implementation. These consistency requirements are not enforced by the compiler but are assumed by code using these traits; violating them causes subtle bugs in collections and algorithms.
Traits in practice: a notification system
Consider designing a notification system that supports multiple output channels: email, SMS, push notifications, logging. The object-oriented approach might define a base Notification class with abstract methods, then subclasses for each channel. The Rust approach uses traits to define the contract and separate types for each channel.
A Notify trait might require a send method taking a message and recipient, returning a Result indicating success or failure:
pub trait Notify { fn send(&self, recipient: &str, message: &str) -> Result<(), NotifyError>; fn send_many(&self, recipients: &[&str], message: &str) -> Result<(), NotifyError> { for recipient in recipients { self.send(recipient, message)?; } Ok(()) }}
pub struct EmailNotifier { smtp_server: String,}
impl Notify for EmailNotifier { fn send(&self, recipient: &str, message: &str) -> Result<(), NotifyError> { // SMTP implementation Ok(()) }}
pub struct SmsNotifier { api_key: String,}
impl Notify for SmsNotifier { fn send(&self, recipient: &str, message: &str) -> Result<(), NotifyError> { // SMS API implementation Ok(()) }
fn send_many(&self, recipients: &[&str], message: &str) -> Result<(), NotifyError> { // Batch API call for efficiency Ok(()) }}Each channel type implements this trait with channel-specific logic. An EmailNotifier uses SMTP. An SmsNotifier uses a third-party API and overrides send_many to use batch operations. Each implementation is independent; there is no shared base class, no inheritance hierarchy, no coupling between implementations.
Generic functions can work with any Notify implementation. A notification scheduler takes N: Notify and calls send at scheduled times. The scheduler knows nothing about emails or SMS; it knows only that N can send notifications. New channels can be added by implementing Notify for new types, requiring no changes to the scheduler.
For heterogeneous channel collections (a system that sends via
multiple channels simultaneously), trait objects provide the solution.
A Vec<Box<dyn Notify>> holds different channel types, calling
send through dynamic dispatch. The notify-all logic iterates over the
collection without knowing the concrete types.
This design demonstrates traits’ advantages over inheritance. Adding a channel requires no modification to existing code; no base class needs updating. Channel implementations share no unnecessary coupling; an SMS implementation need not inherit from an email implementation. Testing is straightforward; mock implementations of Notify can substitute for real channels. The trait defines the minimal contract, and each implementation provides exactly what is needed.
Summary
Traits define behavior contracts that types can implement, serving a role similar to interfaces in object-oriented languages. The separation of trait definition, type definition, and implementation enables flexible composition: you can implement your traits for others’ types and others’ traits for your types (within orphan rule constraints).
Default implementations allow traits to provide convenience methods built on required methods, reducing the burden on implementor while maintaining flexibility. The Iterator trait exemplifies this pattern requiring only next while providing dozens of derived methods.
Trait bounds constrain generic types to those implementing specific traits, enabling generic code that uses trait methods. The compiler generates specialized code for each concrete type, eliminating runtime dispatch overhead. Where clauses provide cleaner syntax for complex bounds.
Associated types define type placeholders that implementations fill in, expressing relationships between implementing types and other types. They differ from generic trait parameters by allowing exactly one implementation per type.
Object safety determines whether traits can be used as trait objects for dynamic dispatch. Trait objects enable heterogeneous collections and runtime polymorphism, trading compile-time type information for flexibility. Static dispatch through generics and dynamic dispatch through trait objects serve different needs; choosing between them reflects whether concrete types are known at compile time.
Supertraits express that implementing one trait requires implementing another, documenting capability dependencies without inheritance.
The next chapter explores generics in depth, examining how generic types and functions work with traits to enable reusable, type-safe abstractions. Monomorphization, the process by which generics become concrete code, reveals how Rust achieves zero-cost abstraction.