Sub topic 2
Readable Bounds with `where` Clauses
Assume you know basic Rust syntax, ownership and borrowing, traits, Option, Result, and Vec. This chapter focuses on how generic bounds affect implementation and dispatch.
Readable Bounds with `where` Clauses
A trait bound restricts which types a generic function accepts. Short bounds fit after the type parameter:
fn show<T: std::fmt::Display>(value: T) {
println!("{value}");
}A where clause moves those restrictions below the signature. This is clearer when several parameters or bounds are involved:
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]));
}A common error is forgetting that every operation in a generic function needs a matching bound. For example, comparing two T values requires T: PartialOrd.
Generic `impl` Blocks and Specialized `impl` Blocks
An impl<T> block adds methods to every Point<T>. A separate block can add methods only when T is a particular type:
struct Point<T> {
x: T,
y: T,
}
impl<T> Point<T> {
fn new(x: T, y: T) -> Self {
Self { x, y }
}
}
impl Point<f64> {
fn distance_from_origin(&self) -> f64 {
(self.x.powi(2) + self.y.powi(2)).sqrt()
}
}
fn main() {
let point = Point::new(3.0, 4.0);
println!("{}", point.distance_from_origin());
}The specialized method is unavailable on Point<i32> because that implementation applies only to Point<f64>.
How the Compiler Compiles Generics
Rust usually uses monomorphization, which means it creates specialized machine code for each concrete type used. A generic function called with i32 and f64 can produce two compiled versions.
This gives static dispatch and usually avoids runtime lookup. The trade-off is that many instantiations can increase compile time and binary size.
`impl Trait` in Arguments and Return Types
impl Trait in an argument position is shorthand for a generic parameter with a bound:
fn shout(text: impl AsRef<str>) -> String {
text.as_ref().to_uppercase()
}
fn make_adder(amount: i32) -> impl Fn(i32) -> i32 {
move |value| value + amount
}
fn main() {
println!("{}", shout("hello"));
let add_three = make_adder(3);
println!("{}", add_three(7));
}In a return position, impl Trait hides one concrete type while preserving static dispatch. It cannot return different unrelated concrete types from different branches.
Exercise
When should you replace inline bounds with a where clause?
Show answer
Use a where clause when several bounds or parameters make the function signature difficult to read.