Sub topic 1
Traits and bounds: the starting point
This chapter sets up the vocabulary the rest of the tutorial relies on. It covers what a trait promises, how a trait bound constrains a generic function, and why the compiler needs to know a concrete type at some point before it can call a method. The later chapters build on that last point to introduce dyn Trait.
Prerequisites
This chapter assumes you already know the following:
- Basic Rust syntax, ownership, and borrowing, including
&and&mutreferences. - How to define a
structand write animplblock for it. - What a generic type parameter such as
Tis, at the level offn largest<T>(items: &[T]). - How to use
Box<T>to put a value on the heap.
You do not need to know anything about trait objects yet. If you can read the examples below without stopping to look up syntax, you are ready.
What a trait is
A trait is a named set of method signatures that a type can promise to provide. A trait can also supply default bodies for some of its methods. A type opts in with an impl Trait for Type block.
trait Shape {
fn area(&self) -> f64;
fn name(&self) -> String {
String::from("shape")
}
}
struct Circle {
r: f64,
}
struct Rect {
w: f64,
h: f64,
}
impl Shape for Circle {
fn area(&self) -> f64 {
std::f64::consts::PI * self.r * self.r
}
fn name(&self) -> String {
String::from("circle")
}
}
impl Shape for Rect {
fn area(&self) -> f64 {
self.w * self.h
}
}
fn main() {
let c = Circle { r: 1.0 };
let r = Rect { w: 2.0, h: 3.0 };
println!("{} {:.2}", c.name(), c.area());
println!("{} {:.2}", r.name(), r.area());
}This prints circle 3.14 and shape 6.00. Rect does not define name, so it uses the default body from the trait. Circle overrides it.
Three facts from this example matter for the rest of the tutorial:
CircleandRectare different types with different sizes.Circleholds onef64andRectholds two.- Both types provide the same method names with the same signatures, so code that only needs
areadoes not care which one it has. - Every call above is made on a value whose concrete type is known at the call site. The compiler can see that
cis aCircle, so it knows exactly whichareato run.
Trait bounds
A trait bound restricts a generic parameter to types that implement a trait. It lets a function accept many types while still being allowed to call the trait's methods on them.
trait Shape {
fn area(&self) -> f64;
}
struct Square(f64);
impl Shape for Square {
fn area(&self) -> f64 {
self.0 * self.0
}
}
fn describe<T: Shape>(item: &T) -> String {
format!("area is {:.1}", item.area())
}
fn main() {
println!("{}", describe(&Square(3.0)));
}This prints area is 9.0. In describe<T: Shape>, the T: Shape part is the bound. Without it, the call item.area() would not compile, because the compiler would know nothing about T and so could not assume it has an area method.
There are three common ways to write the same constraint:
| Form | Example | Notes |
|---|---|---|
| Inline bound | `fn f<T: Shape>(x: &T)` | Shortest form for one bound. |
| `where` clause | `fn f<T>(x: &T) where T: Shape` | Easier to read with several bounds or long types. |
| `impl Trait` in argument position | `fn f(x: &impl Shape)` | Shorthand for an anonymous generic parameter. |
All three mean the same thing for a single parameter. You can combine bounds with +, as in T: Shape + Clone.
Bounds are checked at compile time
The compiler checks every call to a bounded function. If you pass a type that does not implement the trait, you get an error at the call site, not at runtime.
trait Shape {
fn area(&self) -> f64;
}
struct Blob;
fn describe<T: Shape>(item: &T) -> f64 {
item.area()
}
fn main() {
describe(&Blob);
}This program does not compile. The error says that the trait bound Blob: Shape is not satisfied. This is the first of many cases in this tutorial where the compiler's error message tells you exactly which rule you broke.
Generics need a known type
Here is the fact that motivates dyn Trait. A generic parameter T stands for one specific type, chosen by the caller. Inside a single call, every T is the same type.
trait Shape {
fn area(&self) -> f64;
}
struct Circle(f64);
struct Square(f64);
impl Shape for Circle {
fn area(&self) -> f64 {
3.14 * self.0 * self.0
}
}
impl Shape for Square {
fn area(&self) -> f64 {
self.0 * self.0
}
}
fn total_area<T: Shape>(items: &[T]) -> f64 {
items.iter().map(|s| s.area()).sum()
}
fn main() {
let circles = [Circle(1.0), Circle(2.0)];
println!("{:.2}", total_area(&circles));
}This works because the slice holds only Circle values. The following line would not compile:
// Does not compile: array elements must all have the same type.
// let mixed = [Circle(1.0), Square(2.0)];An array, a slice, or a Vec<T> stores elements of one type, and the elements must have the same size so the compiler can compute where element number n starts. Circle and Square happen to be the same size here, but the type check fails regardless. With bounds alone there is no way to say "a list of anything that implements Shape".
What the compiler does with a bound
When the compiler meets a call to a generic function, it substitutes the concrete type for T and generates code for that type. This process is called monomorphization. The next chapter covers it in detail. For now, the useful picture is this:
describe::<Square>anddescribe::<Circle>become two separate compiled functions.- Inside each one,
item.area()is a direct call to a known function. - The choice of which
areato run is made during compilation.
This gives fast code, since direct calls can be inlined. The cost is that the type must be known where the code is compiled. That limit is what the rest of the tutorial works around.
Common errors at this stage
These mistakes come up often when people first combine traits and generics.
- Missing bound. Calling a trait method on
TwithoutT: Traitgives an error such as "no method namedareafound for type parameterT". Fix it by adding the bound. - Forgetting to import the trait. A trait's methods are only callable when the trait is in scope. If the trait is defined in another module, add a
usefor it. - Expecting different types in one
Vec<T>. AVec<T>has a singleT. Two different types that share a trait still do not fit. - Returning different types from
impl Trait. A function returningimpl Shapemust return one concrete type on every path, even though the caller only sees the trait.
The last two items are the usual first encounter with the limits of static types, and they are where dyn Trait enters.
Where this leads
The next chapters follow one thread:
- Generics resolve the concrete type at compile time (static dispatch).
dyn Traitdefers that choice until the program runs (dynamic dispatch).- To make that work, a value of unknown size is placed behind a pointer that also carries a method table.
Everything later in the tutorial, including vtables, dyn compatibility, lifetime bounds, and dyn Any, follows from the trade between these two approaches.
Exercise
A function is declared as fn show<T: Shape>(items: &[T]). You have one Circle and one Square, both implementing Shape. Why can't you pass both in a single slice, and what is the one thing the bound T: Shape does let the function body do?
Show answer
A slice &[T] holds elements of exactly one type, and T is a single concrete type chosen by the caller. Circle and Square are different types, so no T fits both, and the array or slice cannot be built. The bound T: Shape lets the function body call the methods declared in Shape, such as area, on each element. It does not allow mixing types.
Exercise
Rewrite fn total<T: Shape + Clone>(x: &T) -> f64 using a where clause instead of the inline bound.
Show answer
fn total<T>(x: &T) -> f64 where T: Shape + Clone { ... }. The where clause moves the bounds after the signature and means the same thing.