Skip to content
Tutorials Center
My learning

Topics

Lesson 42 of 132 ยท Generics

Trait Bounds and where Clauses

Learn Rust trait bounds: multiple bounds with +, where clauses, impl Trait in arguments and return types, blanket impls and conditional methods.

A bare generic type T can be anything, so inside the function you may do nothing with it. A trait bound narrows the promise: "T can be any type, as long as it implements this trait". The bound is what unlocks operations. If T: Display, you may print a T; if T: PartialOrd, you may compare two of them; if T: Clone, you may copy one.

Bounds are the heart of generic Rust. They make generic code checkable (the compiler verifies the function body against the bounds only), and they document, right in the signature, what a function needs from its inputs. This lesson covers the basic T: Trait syntax, combining bounds, the where clause for readability, impl Trait as a shorthand in arguments and return types, blanket implementations, and methods that only exist when a bound is met. It follows Generics and relies on traits.

Writing a bound

Put the bound after the type parameter, separated by a colon. The largest function that failed in the previous lesson works once T is known to support >.

Rust largest with a PartialOrd bound

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.

The same body now works for integers, floats, string slices and chars, because they all implement PartialOrd. Passing a type that does not is a compile error pointing at the call, not the function body. Here is a struct with no ordering.

Rust Passing a type that breaks the bound (fails on purpose)

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.

The error is error[E0277]: can't compare \Cloud` with `Cloud``, pointing at the call to largest ("required by a bound introduced by this call"), saying that the trait PartialOrd is not implemented for Cloud, and suggesting that you annotate Cloud with #[derive(PartialOrd)] (it also needs PartialEq, which PartialOrd requires as a supertrait). This is the compiler enforcing the bound at the use site. The fix is to implement or derive the trait for Cloud.

Multiple bounds with +

A type can be required to implement several traits at once by joining them with +.

Rust Combining bounds

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.

Copy is needed in report_largest because the function copies elements out of the slice (items[0] and for &item). If you replace it with Clone you write items[0].clone(), which also works for String.

The where clause

Bounds in angle brackets get hard to read as they grow. A where clause moves them after the signature and lets you put each one on its own line. The two forms mean exactly the same.

Rust
fn summarize<K, V>(map: &HashMap<K, V>) -> String
where
    K: Debug + Ord + Hash,
    V: Display,
{
    // ...
}

Besides readability, where can express things the inline form cannot: bounds on types that are not simple parameters, such as Vec<T>: Debug or T::Item: Display, and bounds on associated types (the subject of the next lesson).

Rust A where clause on an iterator

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.

I::Item: Display is a bound on the item type of the iterator, which has no name of its own, so only a where clause can state it. It reads: "I is something that can be iterated, and whatever it yields can be displayed".

impl Trait in argument position

For simple cases, Rust offers a shorthand. fn print_all(items: impl IntoIterator<Item = u32>) declares an anonymous generic parameter with a bound. It is the same as writing fn print_all<I: IntoIterator<Item = u32>>(items: I), just shorter.

Rust impl Trait as an argument

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.

There is one real difference. With the long form <T: Display> you can name T again, for example to force two parameters to be the same type: fn same<T: Display>(a: T, b: T). With impl Display in both positions, each argument may be a different type. Also, callers cannot use the turbofish to pick the type of an impl Trait argument. Use the explicit form when you need to refer to the type; use impl Trait for brevity otherwise.

impl Trait in return position

You can also return impl Trait, which says "I return some single concrete type that implements this trait, but I will not tell you which". It is how you return closures, and long iterator chains whose real type is unreadable, without boxing.

Rust Returning impl Trait

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.

The caller can only use the capabilities named in the trait. In label, you get something Display; you cannot call .len() on it, even though the real type is String. That hides implementation details and lets you change them later without breaking callers.

The word "single" is important: the function must return one concrete type on every path. The next example breaks that rule.

Rust Two different types behind one impl Trait (fails on purpose)

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.

You get error[E0308]: \if` and `else` have incompatible types, because 42is an integer and"forty-two"is a&str. Returning impl Traitdoes not mean "any type that fits", it means "one hidden type". When you really need different types depending on a condition, return aBox` (dynamic dispatch, see Trait objects) or an enum.

Blanket implementations

A blanket implementation implements a trait for every type that satisfies a bound. The standard library does this constantly. impl<T: Display> ToString for T is why every Display type has .to_string(), and impl<T, U: From<T>> Into<U> for T is why From gives you Into.

You can write your own. Suppose you want any type that is Debug to offer a debug_line method.

Rust A blanket implementation

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.

Numbers, strings, vectors and your own struct all gained the method without any of them being edited. That is powerful, and also a reason for care: a blanket impl claims the trait for all matching types, so you cannot later add a specific impl of DebugLine for one of them. And the orphan rule still holds: you can write a blanket impl only for a trait you define (or for a local type). Extension traits like this one are covered further in Advanced trait techniques.

Conditional methods

Bounds can sit on an impl block, so a generic type gets extra methods only when its parameter qualifies. The standard library's Vec<T> has contains only when T: PartialEq, and sort only when T: Ord. Here is the same idea on a type of your own.

Rust Methods that exist only when a bound is met

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.

If you uncomment the last line, the compiler says that the method print_largest exists for Pair<Vec<i32>> but its trait bounds were not satisfied (error[E0599]). This is a strong design tool: the API a user sees changes with the type they chose, and impossible calls are rejected at compile time rather than failing later.

Bounds on structs: usually not needed

You can write struct Cache<K: Hash + Eq, V>, but it is rarely a good idea. A bound on the struct forces every use of the type, including in other impls, to repeat the bound, even where it is not needed. The convention is: put no bounds on the struct, put them on the impl blocks and functions that actually need them. The standard HashMap<K, V> struct has no bounds; only methods such as insert require K: Eq + Hash.

Common bounds you will meet

Bound Gives you
Clone / Copy duplicating a value
Debug / Display formatting with {:?} / {}
PartialEq / Eq ==, and use as a map key (with Hash)
PartialOrd / Ord <, sorting, max / min
Default T::default()
From<X> / Into<X> converting values
Iterator / IntoIterator looping and adapters
Fn, FnMut, FnOnce passing closures
'static owns its data; contains no short-lived borrows
Send / Sync crossing thread boundaries

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does fn show<T: Display>(x: T) promise?

    A trait bound restricts the allowed types to those implementing the trait, and unlocks the trait's operations inside the function.
  2. 2. Which bound is written with a where clause but cannot be written inline next to the parameter?

    A bound on an associated type such as I::Item is not a simple parameter, so it needs a where clause.
  3. 3. Why does this fail? fn pick(flag: bool) -> impl Display { if flag { 42 } else { "x" } }

    A function returning impl Trait must return the same hidden type on every path. Use Box<dyn Display> or an enum to return different types.
  4. 4. What is a blanket implementation?

    A blanket impl is written once for a generic T with bounds and applies to all matching types, which is how ToString and Into are provided.
  5. 5. Where should you normally put a bound like K: Hash + Eq for a generic container?

    Leave the struct unbounded and put bounds on the impls that need them, so users of the type are not forced to repeat unnecessary bounds.

Summary

  • A trait bound (T: Trait) restricts a type parameter and unlocks the trait's methods and operators inside the function.
  • Combine bounds with +, and move long lists into a where clause, which also handles bounds like I::Item: Display.
  • impl Trait in argument position is shorthand for an anonymous generic; in return position it hides one concrete type.
  • A function returning impl Trait must return the same concrete type on every path; otherwise use Box<dyn Trait> or an enum.
  • Blanket implementations (impl<T: Bound> Trait for T) give a trait to every qualifying type, as ToString and Into show.
  • Put bounds on impl blocks to create conditional methods, and keep struct definitions free of bounds.

Next: Associated Types and Generic Traits