Generics and traits.
Describe reusable code through types and capabilities instead of special cases.
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.
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.
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.
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.
fn first<T>(values: &[T]) -> Option<&T> {
values.first()
}
fn main() {
println!("{:?}", first(&[3, 5]));
println!("{:?}", first(&["Rust", "Python"]));
}Some(3)
Some("Rust")- T is inferred separately at the two calls.
- The function borrows any element type.
- 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.
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.
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 });
}12 checks passed
- Summary declares one capability.
- Build implements that behavior using its field.
- 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.
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.