Skip to content
Tutorials Center
My learning

Topics

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.

Rust
fn largest<T>(items: &[T]) -> Option<&T>
where
    T: PartialOrd,
{ /* ... */ }

Try it

Rust Bounds in a where clause

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.

Rust Bounds only where they matter

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

Rust
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) and fn f<T>(t: T) where T: Debug mean the same. Choose where once the line gets long.
  • Needed for associated types. Writing I::Item: Display is only possible in a where clause or as an associated-type bound like I: Iterator<Item: Display> (stable since 1.79).
  • Needed for non-parameter types such as Vec<T>: Debug or &'a T: IntoIterator.
  • where Self: Sized on a trait method keeps it out of the dyn Trait vtable, so the rest of the trait stays object-safe.
  • Conditional impls: putting bounds on the impl (as in Pair<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.