In Rust, when should bounds like `T: Copy + Into<f64>` move into a `where` clause, and what can only a `where` clause express?
answer
- same meaning, different place
- readability once bounds pile up
- left side need not be a parameter
- f64: From<T> versus T: Into<f64>
basics
~20 sInline bounds and a where clause mean the same thing for a type parameter; where is chosen once bounds grow long or numerous. Only where can bound a type that is not a declared parameter, such as f64: From<T> or Vec<T>: Debug.
solid answer
~50 s`fn mean<T: Copy + Into<f64>>(readings: &[T])` and the same function with `where T: Copy + Into<f64>` are identical to the compiler; the Reference says `fn f<A: Copy>()` is the same as `fn f<A>() where A: Copy`. Teams move bounds into `where` once there are several parameters or long `+` lists, so the name, arguments and return type stay readable, and rustfmt then lays out each bound on its own line. The real difference is expressiveness: the left side of a `where` item can be any type, so you can write `f64: From<T>`, `Vec<T>: Debug`, a bound on an associated type or a higher-ranked `for<'a>` bound. Writing `<T, f64: From<T>>` inline instead declares a new type parameter named `f64` that shadows the primitive; rustc only warns about the name there, and the errors surface later in the body.
code
rust · 30 linesfn mean<T>(readings: &[T]) -> Option<f64>
where
T: Copy + Into<f64>,
{
if readings.is_empty() {
return None;
}
let sum: f64 = readings.iter().map(|&r| r.into()).sum();
Some(sum / readings.len() as f64)
}
// The same conversion stated from the target's side: only a where clause can say this.
fn mean_from<T>(readings: &[T]) -> Option<f64>
where
T: Copy,
f64: From<T>,
{
if readings.is_empty() {
return None;
}
let sum: f64 = readings.iter().map(|&r| f64::from(r)).sum();
Some(sum / readings.len() as f64)
}
fn main() {
println!("{:?}", mean(&[2u8, 4, 9]));
println!("{:?}", mean(&[1.5f32, 2.5]));
println!("{:?}", mean_from(&[10i32, 20]));
println!("{:?}", mean::<u16>(&[]));
}go deeper
Recall that inline bounds and where clauses mean the same thing, and that + combines several traits into one requirement.
Explain what only a where clause can say, such as f64: From<T> or Vec<T>: Debug, and why Into is usually preferred over From in bounds.
Spot the inline trap where <T, f64: From<T>> declares a new type parameter, and read an E0277 that mentions From when the signature said Into.
Set a house style for long signatures: where clauses once bounds grow, so public APIs stay readable and adding a bound produces a one-line diff.
## Two spellings of one bound A **trait bound** restricts which types may fill a generic parameter. Rust offers two places to write it: - **inline**, right after the parameter: `fn mean<T: Copy + Into<f64>>(readings: &[T]) -> Option<f64>`; - in a **`where` clause** after the return type: `fn mean<T>(readings: &[T]) -> Option<f64> where T: Copy + Into<f64>`. For a bound on a declared type parameter these are the same thing. The Reference says so directly: bounds written after declaring a generic parameter, `fn f<A: Copy>() {}`, are the same as `fn f<A>() where A: Copy {}`. Nothing about checking, monomorphization or error messages changes. Both forms work on functions, `impl` blocks, structs, enums and traits. ## Combining bounds with `+` `+` joins several traits into one requirement, in either position. In the statistics module, `mean` needs two: - `Copy`, because the closure pattern `|&r|` copies each reading out of the `&T` the iterator yields. Without it rustc reports E0507, "cannot move out of a shared reference". - `Into<f64>`, because `r.into()` turns each reading into an `f64` for the sum. A `where` clause takes a comma-separated list of such items, one per constrained type, and each item can carry its own `+` chain. ## When teams switch to `where` The choice is about reading the signature, and the usual triggers are: - more than one or two traits on a parameter; - several parameters that each carry bounds, as in a cache generic over `K` and `V`; - bounds that mention other parameters, such as `K: Borrow<Q>`; - `impl` blocks, where a long inline list pushes the type being implemented off the screen. rustfmt formats a `where` clause with `where` on its own line and each bound on its own indented line ending in a comma, which keeps diffs small when a bound is added. ## What only a `where` clause can say The Reference describes `where` clauses as "another way to specify bounds on type and lifetime parameters as well as a way to specify bounds on types that aren't type parameters". The left side of a `where` item is any type, not just a parameter name: | `where` item | What it requires | |---|---| | `f64: From<T>` | `f64` can be built from a `T` | | `Vec<T>: Debug` | a vector of `T` can be printed with `{:?}` | | `T::Item: Copy` | the associated type of `T` is `Copy` (covered with associated types) | | `for<'a> &'a C: IntoIterator` | every borrow of `C` can be iterated, whatever its lifetime (covered with higher-ranked bounds) | `f64: From<T>` and `T: Into<f64>` look like the same idea, and std's blanket `impl<T, U> Into<U> for T where U: From<T>` makes every `From` give an `Into`. The difference is direction: std's own documentation for `Into` advises preferring `Into` over `From` in bounds on a generic function, so that types which implement only `Into` are accepted as well. Use `f64: From<T>` when you want to call `f64::from` explicitly or when stating the target type first reads better. ## The inline trap Trying to write the target-side bound inline does not produce an error where you expect one: 1. `fn mean_from<T: Copy, f64: From<T>>(readings: &[T]) -> f64` parses. 2. The `f64` in the angle brackets declares a **new type parameter** that happens to be called `f64` and shadows the primitive. 3. rustc only warns that the type parameter should have an upper camel case name, then fails as soon as the body treats `f64` as the float type: returning a literal `0.0` gives E0308, because the caller chooses what this `f64` is. The fix is always the same: move the bound to a `where` clause. ## Reading the error a bound produces Calling `mean(&totals)` with `totals: [i64; 2]` fails with **E0277**, "the trait bound `f64: From<i64>` is not satisfied", plus the note "required for `i64` to implement `Into<f64>`". The message names `From` because `Into` comes from the blanket impl. rustc also lists the `From` impls that `f64` has: among the numeric types, std converts losslessly from `i8`, `i16`, `i32`, `u8`, `u16`, `u32` and `f32`, and not from `i64` or `u64`, whose values can exceed the 53-bit precision of an `f64`. Callers with 64-bit totals convert explicitly with `as f64` before calling, or the module offers a separate function for them.
- Why does `mean` need `Copy` in addition to `Into<f64>`?The iterator yields `&T`, and the closure pattern `|&r|` copies the reading out of the reference. Without `T: Copy` rustc reports E0507, "cannot move out of a shared reference". The alternative is `T: Clone` with `r.clone().into()`; for the small numeric types `mean` targets, `Copy` costs nothing and reads more simply.
- Is `T: Into<f64>` or `f64: From<T>` the better bound for `mean`?Usually `T: Into<f64>`. std's documentation for `Into` recommends preferring it in bounds on generic functions so that types implementing only `Into` are accepted too; every `From` impl already yields an `Into` through the blanket impl. `f64: From<T>` is fine when you want to call `f64::from` explicitly, but it can only be written in a where clause.
- Do bounds written in a where clause on an `impl` block behave any differently from inline ones?No. `impl<K: Eq + Hash, V> Cache<K, V>` and `impl<K, V> Cache<K, V> where K: Eq + Hash` are the same impl. Either way the bounds limit which `Cache` instantiations get that block's methods; the where form just keeps the implemented type readable when the list is long.
- A where clause is checked later than inline bounds, so it is more permissive.
- Where clauses are allowed on impl blocks but not on plain functions.
- Writing fn f<T, f64: From<T>> puts a bound on the primitive f64.
- Several traits on one parameter need separate where lines, because + only works inline.
- A T: Into<f64> bound accepts every numeric type, including i64 and u64.