Sub topic 1
Quick recap: traits and generic bounds
Associated types and generic associated types (GATs) are features of traits, so they only make sense once traits and bounds feel routine. This chapter reviews the working model you need and the errors that show up most often. It ends with a short example of a design problem that the next chapters solve.
Prerequisites
This chapter assumes you can already do the following:
- Define a trait and implement it for a struct, including methods with default bodies.
- Write a generic function with a bound such as
T: Display. - Read basic lifetime annotations like
&'a strand know the borrowing rules (one mutable borrow or many shared borrows). - Use
Iteratorwithforloops and adapters likemapandfilter.
If any of these are shaky, spend a few minutes with the Rust Book chapters on traits, generics, and lifetimes first. Nothing here is new material. It is the vocabulary the rest of the tutorial uses.
What a trait is
A trait is a named set of method signatures that a type promises to provide. A trait can also give default bodies for some methods, and implementers may override them.
A trait does not describe data. It describes behavior. Two unrelated types can both implement Shape without sharing fields or a parent type.
The program below defines a trait with one required method and one default method. It then uses the trait in two ways: through a generic function (static dispatch) and through trait objects (dynamic dispatch).
use std::f64::consts::PI;
trait Shape {
fn area(&self) -> f64;
fn describe(&self) -> String {
format!("shape with area {:.2}", self.area())
}
}
struct Square(f64);
struct Circle {
radius: f64,
}
impl Shape for Square {
fn area(&self) -> f64 {
self.0 * self.0
}
}
impl Shape for Circle {
fn area(&self) -> f64 {
PI * self.radius * self.radius
}
fn describe(&self) -> String {
format!("circle of radius {}", self.radius)
}
}
fn print_description<T: Shape>(item: &T) {
println!("{}", item.describe());
}
fn total_area(shapes: &[Box<dyn Shape>]) -> f64 {
shapes.iter().map(|s| s.area()).sum()
}
fn main() {
print_description(&Square(2.0));
print_description(&Circle { radius: 1.0 });
let shapes: Vec<Box<dyn Shape>> = vec![
Box::new(Square(2.0)),
Box::new(Circle { radius: 1.0 }),
];
println!("{:.2}", total_area(&shapes));
}The program prints:
shape with area 4.00
circle of radius 1
7.14Square uses the default describe. Circle overrides it.
Generic bounds
A bound restricts a type parameter to types that implement certain traits. Inside the function, the bound is the only information the compiler has about T. You can call a method on a T value only if some bound provides that method.
The following function needs two capabilities from its element type: comparing values and printing them. It lists both as bounds in a where clause.
use std::fmt::Display;
fn show_largest<T>(items: &[T]) -> Option<String>
where
T: PartialOrd + Display,
{
let mut iter = items.iter();
let mut best = iter.next()?;
for item in iter {
if item > best {
best = item;
}
}
Some(format!("largest: {}", best))
}
fn main() {
println!("{:?}", show_largest(&[3, 9, 4]));
println!("{:?}", show_largest::<i32>(&[]));
}The program prints Some("largest: 9") and then None.
A few points about the syntax:
T: A + BmeansTmust implement both traits.fn f<T: Display>(x: T)andfn f<T>(x: T) where T: Displaymean the same thing. Usewherewhen the bounds get long or when they constrain something other than a bare parameter. Later chapters rely on that second case.fn f(x: impl Display)is shorthand for an anonymous type parameter with that bound. You cannot name that parameter, so you cannot write turbofish arguments for it or refer to it in other bounds.
Static dispatch and monomorphization
When you call a generic function, the compiler generates a separate copy of it for each concrete type used. This process is called monomorphization. print_description::<Square> and print_description::<Circle> become two ordinary functions, and each call to describe is resolved at compile time. The trade-offs:
- Calls can be inlined, so a bound costs nothing at run time.
- Each distinct type adds compiled code, which can grow binary size and compile time.
- Every value of a type parameter must have one concrete type at each use. A
Vec<T>holds onlyTs, not a mix.
Dynamic dispatch
dyn Shape is a trait object. It is a pointer (such as Box<dyn Shape> or &dyn Shape) paired with a table of function pointers called the vtable. The concrete type is forgotten at compile time, and method calls go through the vtable at run time. That lets one Vec hold squares and circles together.
Not every trait can be used as dyn Trait. A trait is dyn compatible only if the compiler can build a vtable for it. For example, a method that returns Self or has its own type parameters breaks that. The error code is E0038. This matters again when we reach associated types and GATs.
Traits with generic parameters
A trait can itself take type parameters. The standard library's From<T> is the usual example. A single type may implement such a trait several times, once for each choice of the parameter.
struct Meters(f64);
struct Feet(f64);
struct Inches(f64);
impl From<Feet> for Meters {
fn from(f: Feet) -> Meters {
Meters(f.0 * 0.3048)
}
}
impl From<Inches> for Meters {
fn from(i: Inches) -> Meters {
Meters(i.0 * 0.0254)
}
}
fn main() {
let a = Meters::from(Feet(10.0));
let b: Meters = Inches(100.0).into();
println!("{:.2} {:.2}", a.0, b.0);
}The program prints 3.05 2.54. Both impls coexist because From<Feet> and From<Inches> are different traits as far as the compiler is concerned. The compiler picks the right one from the argument type.
That freedom is useful here, but it is not always what you want. The next section shows a case where it gets in the way.
A design problem to carry forward
Suppose a trait describes a collection and has a method that returns the first element. The element type belongs to the implementer. A stack of i32 holds i32, and a stack of String holds String. With only the tools above, you would add a type parameter to the trait:
trait Container<T> {
fn first(&self) -> Option<&T>;
}
struct Stack<T> {
items: Vec<T>,
}
impl<T> Container<T> for Stack<T> {
fn first(&self) -> Option<&T> {
self.items.first()
}
}
fn describe<C: Container<i32>>(c: &C) -> String {
format!("{:?}", c.first())
}
fn main() {
let s = Stack { items: vec![10, 20, 30] };
println!("{}", describe(&s));
}This prints Some(10), and it works. Two things are awkward, though:
- Every function that accepts a
Containermust also name the element type, even when it does not care about it.Container<i32>appears in the bound above. - Nothing stops someone from implementing both
Container<i32>andContainer<String>for one type. The "element type" is then not a single fact about the type.
Associated types remove both problems. The trait declares a placeholder, and each implementation fills it in exactly once. That is the subject of the next chapter.
Common errors
The table lists compiler errors you will meet while working with the rest of this tutorial, and what each one usually means.
| Error | Typical cause | Fix |
|---|---|---|
| E0599, no method named `x` found for type parameter `T` | The function body calls a method that no bound on `T` provides | Add the bound that declares the method |
| E0369, binary operation `>` cannot be applied to type `T` | An operator is used without the matching trait bound (`PartialOrd`, `Add`) | Add `T: PartialOrd` or the relevant operator trait |
| E0277, the trait bound `X: Trait` is not satisfied | A caller passes a type that does not implement the required trait | Implement the trait for `X`, or change the call |
| E0117, only traits defined in the current crate can be implemented for types defined outside of the crate | An impl breaks the orphan rule | Wrap the foreign type in a local newtype |
| E0038, the trait is not dyn compatible | `dyn Trait` is used on a trait with methods that cannot go in a vtable | Add `where Self: Sized` to those methods, or use generics |
| E0308, mismatched types when returning `impl Trait` | Different branches return different concrete types | Return one concrete type, or box as `Box<dyn Trait>` |
A related rule is coherence. For any given trait and type, at most one impl may apply. The compiler rejects overlapping impls such as impl<T: Display> Describe for T alongside impl Describe for i32, because i32 matches both.
Habits to keep
- Put the narrowest bounds on a function that make its body compile. Extra bounds shrink the set of callers for no benefit.
- Prefer a
whereclause once a signature has more than one or two bounds. - Use generics when the caller knows the concrete type and you want speed. Use
dyn Traitwhen you need a mixed collection or want to limit compile-time code growth. - Read the compiler's "required by a bound in" note. It points at the exact bound that failed and usually names the missing impl.
Exercise
The function fn biggest<T>(a: T, b: T) -> T { if a > b { a } else { b } } fails to compile. Which error code do you expect, and what is the smallest change that fixes it?
Show answer
E0369, because > needs PartialOrd and T has no bounds. Change the signature to fn biggest<T: PartialOrd>(a: T, b: T) -> T (or add a where T: PartialOrd clause).
Exercise
Why can a Vec<Box<dyn Shape>> hold both Square and Circle, while a Vec<T> with T: Shape cannot?
Show answer
Vec<T> is monomorphized, so T is one concrete type per use and all elements share it. Box<dyn Shape> erases the concrete type behind a pointer and a vtable. Every element then has the same type, Box<dyn Shape>, and method calls are resolved at run time.
Exercise
In the Container<T> example, why can a single type implement both Container<i32> and Container<String>, and why might that be unwanted for an "element type"?
Show answer
A trait with different type arguments is a different trait for each argument, so the impls do not overlap. An element type should be one fact about the implementing type, but the generic parameter lets the same type claim several element types. Associated types (next chapter) allow exactly one choice per implementation.