Rust Reference ยท Keywords and Statements
The where clause
Reference for Rust where clauses: moving trait bounds out of angle brackets, bounds on associated types and references, higher-ranked bounds and Self: Sized.
A where clause lists the constraints a generic item needs. It says the same thing as bounds written inside <...>, but it reads better when there are several bounds, and it can express constraints that angle brackets cannot, such as bounds on associated types or on arbitrary types like Vec<T>.
where can follow functions, structs, enums, traits, impl blocks and type aliases.
fn largest<T>(items: &[T]) -> Option<&T> where T: PartialOrd, { /* ... */ }
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.
Syntax
where Type: Bound + Bound, 'a: 'b, for<'x> Type: Trait<'x>, Type::Assoc: Bound,
| Part | Description |
|---|---|
Type: Bound |
The type must implement the trait (or outlive the lifetime). The left side can be any type, not only a parameter. |
'a: 'b |
Lifetime bound: 'a outlives 'b. |
for<'x> |
Higher-ranked trait bound: the bound must hold for every lifetime 'x. |
?Sized |
Relaxes the implicit Sized bound: T: ?Sized. |
Usage notes
- Equivalent to inline bounds.
fn f<T: Debug>(t: T)andfn f<T>(t: T) where T: Debugmean the same. Choosewhereonce the line gets long. - Needed for associated types. Writing
I::Item: Displayis only possible in awhereclause or as an associated-type bound likeI: Iterator<Item: Display>(stable since 1.79). - Needed for non-parameter types such as
Vec<T>: Debugor&'a T: IntoIterator. where Self: Sizedon a trait method keeps it out of thedyn Traitvtable, so the rest of the trait stays object-safe.- Conditional impls: putting bounds on the
impl(as inPair<T>above) gives methods only to types that qualify, without restricting the struct itself. - Struct bounds are viral. If a struct declares
where T: Display, every impl must repeat the bound. Prefer to leave bounds off the type and put them on the impls. - Constraint order does not matter; the compiler collects them all.