Sub topic 5
Readable bounds with where clauses
Prerequisites
This chapter assumes you can write a generic function, add an inline trait bound such as T: Display, and read a trait path like std::fmt::Debug. It builds on the trait bounds chapter. It adds no new capabilities for ordinary bounds. It changes where you write them, and it allows a few bounds that the inline form cannot express.
The problem: crowded signatures
Inline bounds sit inside the angle brackets. Each new bound pushes the function name and its parameters further to the right:
use std::fmt::{Debug, Display};
fn describe<T: Display + Clone, U: Debug + PartialEq + Clone>(label: T, value: U) -> String {
format!("{label}: {value:?}")
}
fn main() {
println!("{}", describe("numbers", vec![1, 2, 3]));
}This compiles, but the signature is hard to scan. With four or five bounds it becomes unreadable.
Moving bounds into a where clause
A where clause lists the same bounds after the return type and before the body:
use std::fmt::{Debug, Display};
fn describe<T, U>(label: T, value: U) -> String
where
T: Display,
U: Debug,
{
format!("{label}: {value:?}")
}
fn main() {
println!("{}", describe("numbers", vec![1, 2, 3]));
}The rules are short:
wherecomes after the return type and before the opening{.- Each bound is separated by a comma. A trailing comma is allowed.
- The angle brackets keep only the parameter names.
- You can combine bounds with
+, for exampleT: Display + Clone.
The two forms mean exactly the same thing. The compiler produces identical code for both.
Bounds that only where can express
A where clause can constrain any type, not only a bare parameter. Inline bounds cannot do this. The most common case is a bound on an associated type:
use std::fmt::Display;
fn print_all<I>(items: I)
where
I: IntoIterator,
I::Item: Display,
{
for item in items {
println!("{item}");
}
}
fn main() {
print_all(vec![1, 2, 3]);
print_all(["a", "b"]);
}I::Item is the type of the values the iterator yields. It is not a parameter you declared, so there is nowhere to write its bound inline. You can also write bounds such as Vec<T>: Debug or &'a T: IntoIterator this way.
Where clauses on impl blocks
An impl block can carry a where clause. Methods in that block exist only when the bound holds:
use std::fmt::Display;
struct Wrapper<T>(T);
impl<T> Wrapper<T>
where
T: Display,
{
fn show(&self) -> String {
format!("[{}]", self.0)
}
}
fn main() {
println!("{}", Wrapper(5).show());
}Wrapper<T> can hold any type. Calling show on a Wrapper whose T lacks Display is a compile error.
Choosing between the two forms
| Situation | Prefer |
|---|---|
| One parameter, one short bound | Inline: `fn f<T: Copy>(x: T)` |
| Several parameters or several bounds | `where` |
| Bound on an associated type or a compound type | `where` (required) |
| Bounds on an `impl` block that make the header long | `where` |
Common errors
- Placing
whereafter the body. It must come before the{. - Declaring a bound for a name you never declared. In
where U: Debug,Umust appear in the angle brackets, unless it is a type such asI::ItemorVec<T>. - Leaving out a bound the body needs. If the body prints with
{}and you only wroteT: Debug, you get error E0277, "Tdoesn't implementDisplay". Add the missing bound to the clause.
Exercise
Write the signature of a function sum_all that takes any I that implements IntoIterator whose items are i32, and returns an i32. Use a where clause.
Show answer
fn sumall<I>(items: I) -> i32
where
I: IntoIterator<Item = i32>,
{
items.intoiter().sum()
}
The bound Item = i32 fixes the associated type, so the body can call sum and get an i32.