Where clauses
A bound can also be expressed using a where clause immediately
before the opening {, rather than at the type’s first mention.
Additionally, where clauses can apply bounds to arbitrary types,
rather than just to type parameters.
Some cases that a where clause is useful:
- When specifying generic types and bounds separately is clearer:
1. impl <A: TraitB + TraitC, D: TraitE + TraitF> MyTrait<A, D> for YourType {}
3. // Expressing bounds with a `where` clause
4. impl <A, D> MyTrait<A, D> for YourType where
5. A: TraitB + TraitC,
6. D: TraitE + TraitF {}
- When using a
whereclause is more expressive than using normal syntax. Theimplin this example cannot be directly expressed without awhereclause:
1. use std::fmt::Debug;
3. trait PrintInOption {
4. fn print_in_option(self);
5. }
7. // Because we would otherwise have to express this as `T: Debug` or
8. // use another method of indirect approach, this requires a `where` clause:
9. impl<T> PrintInOption for T where
10. Option<T>: Debug {
11. // We want `Option<T>: Debug` as our bound because that is what's
12. // being printed. Doing otherwise would be using the wrong bound.
13. fn print_in_option(self) {
14. println!("{:?}", Some(self));
15. }
16. }
18. fn main() {
19. let vec = vec![1, 2, 3];
21. vec.print_in_option();
22. }
