where clause
- Rust course
- Intermediate
- Lesson 21/115
- 4 min
Write long trait bounds readably with where.
The where clause
When bounds get long, the signature becomes unreadable. The where clause moves the bounds to the end of the signature:
use std::fmt::{Debug, Display};
fn ozetle<T, U>(a: &T, b: &U) -> String
where
T: Display,
U: Debug,
{
format!("{a} / {b:?}")
}The meaning is the same; only the syntax differs. With several type parameters or long bounds, where is preferred.
Associated type bounds
where is also used to bound a trait's associated type. For example, printing the elements of any iterator:
fn hepsini_yaz<I>(it: I)
where
I: Iterator,
I::Item: std::fmt::Display,
{
for x in it {
print!("{x} ");
}
println!();
}
hepsini_yaz([1, 2, 3].iter()); // 1 2 3Practice Summarize
Write the ozetle function above with where. Print the result of ozetle(&42, &vec![1, 2]).
Starter code
use std::fmt::{Debug, Display};
fn main() {
// buraya yaz
}Sample solution
use std::fmt::{Debug, Display};
fn ozetle<T, U>(a: &T, b: &U) -> String
where
T: Display,
U: Debug,
{
format!("{a} / {b:?}")
}
fn main() {
println!("{}", ozetle(&42, &vec![1, 2]));
}Expected output
42 / [1, 2]
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Which can be written with <code>where</code> but not as an inline bound?
- T: Display
- T: Clone + Debug
- None
- Bounds on types that aren't type parameters: where Vec<T>: Debug Correct answer
Explanation: where is more flexible; it allows bounds on complex types and associated types (T::Item: Display).
2 Move the bounds to the end
fn ozetle<T, U>(a: &T, b: &U) -> String
____
T: Display,
U: Debug,
{
format!("{a} / {b:?}")
}
fn ozetle<T, U>(a: &T, b: &U) -> String
where
T: Display,
U: Debug,
{
format!("{a} / {b:?}")
}
Explanation: The where clause lists the bounds after the signature.
3 Syntax and meaning
| Term | Meaning |
|---|---|
fn f<T: Display>(x: T) |
Inline bound |
where T: Display |
where bound |
I::Item: Display |
Associated type bound |
T: Display, U: Debug |
Two parameters, two bounds |