Sub topic 1
Traits and bounds: the starting point
Prerequisites
This chapter assumes you can read basic Rust syntax and you understand ownership and borrowing. You should be able to define a struct and write an impl block. You should have seen generics like Vec<T> and used Box and references. Later chapters build on the trait basics reviewed here.
What a trait gives you
A trait is a named set of methods that a type can promise to provide. Code that only needs those methods can work with any type that makes the promise. A trait can also supply default method bodies, which an implementor may keep or override.
trait Shape {
fn area(&self) -> f64;
fn describe(&self) -> String {
format!("a shape with area {:.2}", self.area())
}
}
struct Square(f64);
struct Circle(f64);
impl Shape for Square {
fn area(&self) -> f64 {
self.0 * self.0
}
}
impl Shape for Circle {
fn area(&self) -> f64 {
std::f64::consts::PI * self.0 * self.0
}
fn describe(&self) -> String {
format!("a circle with radius {}", self.0)
}
}
fn main() {
println!("{}", Square(2.0).describe());
println!("{}", Circle(1.0).describe());
}Square keeps the default describe. Circle overrides it. Both are checked against the trait at compile time, so a missing area is a compile error.
Trait bounds
A trait bound restricts a generic type parameter to types that implement a trait. The compiler uses the bound to decide which methods you may call on the value.
trait Shape {
fn area(&self) -> f64;
}
struct Square(f64);
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 squares = [Square(1.0), Square(2.0)];
println!("{}", total_area(&squares));
}Here T: Shape is the bound. Without it, s.area() would not compile, because T could be any type.
You can write the same bound in three ways:
| Form | Example |
|---|---|
| Inline bound | `fn f<T: Shape>(x: &T)` |
| `where` clause | `fn f<T>(x: &T) where T: Shape` |
| `impl Trait` argument | `fn f(x: &impl Shape)` |
Use a where clause when there are several bounds, since it keeps the signature readable. Combine bounds with +, as in T: Shape + Clone.
One type, one choice
In total_area, the slice holds one type T. You cannot put a Square and a Circle in the same &[T], because T is a single concrete type for each call. The compiler picks that type, then generates code for it.
This is a good default, but it leaves one question open. What if the concrete types are only known at runtime, or you need one collection holding several types? Bounds alone cannot express that. The chapters that follow introduce dyn Trait to answer it.
Common errors
- Calling a method that the bound does not provide. The compiler reports that the method is not found for type parameter
T. Add the missing trait to the bound. - Forgetting to import a trait. A trait method is only callable when the trait is in scope. If it lives in another module, add a
useline. - Mixing types in a generic slice or
Vec<T>. The error is a type mismatch, since all elements must share one type.
Exercise
Why does fn total<T: Shape>(items: &[T]) reject a slice that mixes Square and Circle values?
Show answer
T stands for one concrete type per call, and a slice holds elements of a single type. Both Square and Circle implement Shape, but the bound does not let different types share one slice. Handling mixed types needs trait objects, which later chapters cover.