Skip to chapter content
navan✳THE BUILD LABRUST / GUIDE
0/26 read
CHAPTER 10 / 21 · ABSTRACTION

Generics and traits.

Describe reusable code through types and capabilities instead of special cases.

BY NAVAN SAMILONG READRUST 2024THEORY FIRST
01 / THE MENTAL MODEL

The idea behind the syntax.

A generic function or type describes a shape of computation without naming one concrete data type. The compiler still creates type-safe code: a generic parameter is constrained by the operations the function needs. A trait names a capability, such as being displayable, comparable, or iterable. A bound like T: Display says which operation is available without requiring every T to be the same concrete type.

Generics are not a license to hide design. A function that asks for many unrelated trait bounds may really be performing several responsibilities. Conversely, a precise trait can make a public API more flexible: a caller supplies any type that satisfies the capability, and the function can rely on that contract. Traits also let different types provide their own implementation of a shared operation.

02 / THE RULES

What Rust is checking.

Rust normally uses static dispatch for generic code: at compile time it knows the concrete type used at a call site and can generate suitable code. This can enable optimisation but can increase compiled code size. Trait bounds can be written directly or in a where clause when several relationships need room to breathe. Associated types describe a type chosen by a trait implementation, while generic trait parameters describe types chosen at use sites.

A trait's default method provides shared behavior, but an implementation may override it when allowed. The orphan rules restrict which external traits you may implement for which external types, protecting compatibility across crates. The examples below make the contract visible: examine which operations the body uses, then look at the bound that promises them.

03 / CODE, EXPLAINED

See the rule in context.

Each example isolates one part of the model. Follow the bindings, types, ownership transfers, and possible outcomes line by line.

EXAMPLE 01

Generics & type parameters

A generic parameter stands for a type chosen by the caller or inferred from usage. The function body still has to be valid for its declared bounds. Rust normally monomorphizes generic functions into concrete versions used by the program, so generic code does not automatically imply dynamic dispatch. Start with the operations the algorithm needs and express those as bounds. Prefer a small clear generic function over a highly abstract signature that makes everyday calls hard to understand.

generics.rs
fn first<T>(values: &[T]) -> Option<&T> {
    values.first()
}
fn main() {
    println!("{:?}", first(&[3, 5]));
    println!("{:?}", first(&["Rust", "Python"]));
}
OUTPUT
Some(3)
Some("Rust")
  1. T is inferred separately at the two calls.
  2. The function borrows any element type.
  3. No Copy bound is necessary because it returns a reference.

The boundary: A generic T does not automatically support addition, comparison, formatting, or cloning. Declare only the capabilities required.

EXAMPLE 02

Traits & implementations

A trait describes behavior that types can implement. A trait method can have a default body, and an impl provides the type-specific behavior. Bounds such as T: Summary let a function rely on that capability without knowing the concrete type. Traits are also used for standard operations such as Debug, Clone, Iterator, and From. Keep the contract cohesive: a type that can summarize itself need not also know how to persist itself or serve an HTTP request.

traits.rs
trait Summary {
    fn summary(&self) -> String;
}
struct Build {
    passed: u32,
}
impl Summary for Build {
    fn summary(&self) -> String {
        format!("{} checks passed", self.passed)
    }
}
fn report(item: &impl Summary) {
    println!("{}", item.summary());
}
fn main() {
    report(&Build { passed: 12 });
}
OUTPUT
12 checks passed
  1. Summary declares one capability.
  2. Build implements that behavior using its field.
  3. The report function accepts any type implementing Summary.

The boundary: You generally need to own either the trait or the type to implement that trait for the type; this coherence rule avoids conflicting implementations.

04 / THE CONNECTION

Keep this model.

A generic names what may vary; a trait names what must remain possible. The combination lets code reuse an idea without giving up type checking.

Finished reading?
Built with curiosity. By Navan Sami. ↗Rust · The rules behind the code.