Sub topic 5
Readable bounds with where clauses
This chapter assumes you can write a generic function with a type parameter, and that you know how to add a trait bound such as T: Display. It also assumes you have used Iterator and IntoIterator at a basic level. Here you will learn the where clause: what it means, when it is only a style choice, and when it is the only way to write a bound.
Inline bounds and where clauses mean the same thing
A bound can sit directly after the parameter name, inside the angle brackets. It can also move to a where clause after the signature. For ordinary type parameters the compiler treats the two forms identically.
use std::fmt::{Debug, Display};
fn describe_inline<T: Display, U: Debug>(label: T, value: U) -> String {
format!("{label}: {value:?}")
}
fn describe_where<T, U>(label: T, value: U) -> String
where
T: Display,
U: Debug,
{
format!("{label}: {value:?}")
}
fn main() {
println!("{}", describe_inline("numbers", vec![1, 2, 3]));
println!("{}", describe_where("numbers", vec![1, 2, 3]));
}Both functions produce numbers: [1, 2, 3]. The only difference is how the signature reads.
A where clause is a comma-separated list of predicates. Each predicate has a type on the left, a colon, and one or more bounds joined by +. A trailing comma is allowed, and rustfmt adds one. The order of predicates does not matter.
Why readability matters
Inline bounds work well for one short bound. Three bounds on three parameters make the signature hard to scan, because the parameter list, the bounds, the arguments, and the return type are all packed into one line:
use std::collections::HashMap;
use std::fmt::{Debug, Display};
use std::hash::Hash;
fn report<K: Display + Hash + Eq + Clone, V: Debug + Clone, S: std::hash::BuildHasher>(map: &HashMap<K, V, S>) -> Vec<String> {
map.iter().map(|(k, v)| format!("{k} => {v:?}")).collect()
}The where form separates the shape of the function from its requirements:
use std::collections::HashMap;
use std::fmt::{Debug, Display};
use std::hash::{BuildHasher, Hash};
fn report<K, V, S>(map: &HashMap<K, V, S>) -> Vec<String>
where
K: Display + Hash + Eq,
V: Debug,
S: BuildHasher,
{
map.iter().map(|(k, v)| format!("{k} => {v:?}")).collect()
}
fn main() {
let mut m = HashMap::new();
m.insert("a", 1);
for line in report(&m) {
println!("{line}");
}
}The first line now shows only the names and the types in play. The requirements are listed one per line below it. This version also drops the Clone bounds, which the body never used. Short lines make it easier to see which bounds are unnecessary.
A common rule of thumb is to use inline bounds when there is a single, short bound, and to switch to where as soon as the signature wraps or a parameter has several bounds.
What only a where clause can express
Inline bounds can only constrain the parameter they are attached to. A where clause can constrain any type that appears in the signature, which makes it strictly more powerful.
| Need | Inline bound | where clause |
|---|---|---|
| `T: Display` | yes | yes |
| Bound on an associated type, such as `I::Item: Display` | no | yes |
| Bound on a composed type, such as `Vec<T>: Debug` | no | yes |
| Bound on `Self` in a trait method | no | yes |
| Higher-ranked bounds with `for<'a>` on a reference type | no | yes |
Bounds on associated types
The most common case is constraining the item type of an iterator. IntoIterator has an associated type Item, and you cannot write that constraint in the angle brackets.
use std::fmt::Display;
fn print_all<I>(iter: I)
where
I: IntoIterator,
I::Item: Display,
{
for item in iter {
println!("{item}");
}
}
fn main() {
print_all(vec![1, 2, 3]);
print_all(["a", "b"]);
}The predicate I::Item: Display has a type on the left that is not a parameter, so it needs a where clause. The same applies when you fix an associated type, as in I: Iterator<Item = u32>. That form is legal inline, but it often reads better in where once other bounds are present.
Bounds on composed types
The left side of a predicate can be any type that mentions your parameters:
use std::fmt::Debug;
fn dump<T>(items: Vec<T>)
where
Vec<T>: Debug,
{
println!("{items:?}");
}
fn main() {
dump(vec![1, 2, 3]);
}Here Vec<T>: Debug holds exactly when T: Debug. Writing T: Debug is usually clearer. The composed form is useful when the relationship is easy to state on the container but awkward to derive from the element, for example when a generic wrapper needs Wrapper<T>: Serialize and you do not want to list every bound that implies.
Arithmetic bounds
Operator traits have an associated Output type, so numeric generics often need where:
use std::ops::Add;
fn add_twice<T>(a: T, b: T) -> T
where
T: Add<Output = T> + Copy,
{
a + b + b
}
fn main() {
println!("{}", add_twice(1, 2));
println!("{}", add_twice(1.5, 0.25));
}Add<Output = T> says that adding two T values yields a T again, which is what lets the result feed into the second +. Copy is needed because b is used twice.
Where clauses on impl blocks and methods
A where clause can follow an impl header or an individual method. This lets you offer a method only when a condition holds, without splitting the type into separate impl blocks per concrete type.
use std::fmt::Display;
struct Wrapper<T> {
inner: T,
}
impl<T> Wrapper<T> {
fn new(inner: T) -> Self {
Wrapper { inner }
}
fn show(&self) -> String
where
T: Display,
{
format!("[{}]", self.inner)
}
}
impl<T> Wrapper<T>
where
T: Clone,
{
fn duplicate(&self) -> (T, T) {
(self.inner.clone(), self.inner.clone())
}
}
fn main() {
let a = Wrapper::new(5);
println!("{}", a.show());
println!("{:?}", a.duplicate());
let b = Wrapper::new(vec![1, 2]);
println!("{}", b.inner.len());
println!("{:?}", b.duplicate());
// b.show() would not compile: Vec<i32> does not implement Display.
}Wrapper<T> exists for every T. show exists only when T: Display, and duplicate only when T: Clone. Calling a method whose bound is not met gives a compile error at the call site. That is different from putting the bound on the struct itself.
Where Self: Sized on trait methods
A trait method can carry its own where clause. The bound where Self: Sized is the standard way to keep a trait usable as dyn Trait while still offering methods that need a known size.
trait Shape {
fn area(&self) -> f64;
fn boxed(self) -> Box<dyn Shape>
where
Self: Sized + 'static,
{
Box::new(self)
}
}
struct Square(f64);
impl Shape for Square {
fn area(&self) -> f64 {
self.0 * self.0
}
}
fn main() {
let shape = Square(2.0).boxed();
println!("{}", shape.area());
}boxed takes self by value, which a trait object cannot do because its size is unknown. The Self: Sized bound excludes boxed from the dyn Shape vtable, so dyn Shape remains valid. The 'static bound is needed because Box<dyn Shape> defaults to a 'static trait object. Neither bound can be written inline, since Self is not a declared parameter.
Choosing between the two forms
The next diagram summarizes the decision.
Common errors
- Missing a bound the body needs. Writing
a > bon an unboundedTfails with an error that the binary operation cannot be applied toT. The compiler suggests addingT: PartialOrd. Add it to thewhereclause. - Forgetting the associated type bound. Printing
I::Itemwith{}fails unless you addI::Item: Display. BoundingI: IntoIteratoralone says nothing about the items. - Over-bounding. Adding
CloneorCopy"just in case" restricts callers for no reason. Add a bound when the compiler asks for it. - Repeating a parameter in two predicates.
where T: Display, T: Debugis legal and means the same asT: Display + Debug. It is useful mainly when predicates come from different sources, such as macros. - Leaving out
Output = T.T: Addalone does not guarantee thata + bhas typeT, so returning it fails to type-check.
Exercise
Rewrite fn total<I: Iterator<Item = T>, T: std::ops::Add<Output = T> + Default>(iter: I) -> T so that every bound is in a where clause, and write the body so that it sums the items starting from T::default(). Which bound could not have been moved out of a where clause if it had been written as I::Item: Copy instead?
Show answer
fn total<I, T>(iter: I) -> T where I: Iterator<Item = T>, T: std::ops::Add<Output = T> + Default { let mut acc = T::default(); for x in iter { acc = acc + x; } acc }. A bound written as I::Item: Copy constrains an associated type rather than a declared parameter, so it can only be written in a where clause. The two original bounds were on plain parameters, so either form worked for them.