]> git.proxmox.com Git - rustc.git/blob - src/doc/rust-by-example/src/generics/where.md
New upstream version 1.37.0+dfsg1
[rustc.git] / src / doc / rust-by-example / src / generics / where.md
1 # Where clauses
2
3 A bound can also be expressed using a `where` clause immediately
4 before the opening `{`, rather than at the type's first mention.
5 Additionally, `where` clauses can apply bounds to arbitrary types,
6 rather than just to type parameters.
7
8 Some cases that a `where` clause is useful:
9
10 * When specifying generic types and bounds separately is clearer:
11
12 ```rust,ignore
13 impl <A: TraitB + TraitC, D: TraitE + TraitF> MyTrait<A, D> for YourType {}
14
15 // Expressing bounds with a `where` clause
16 impl <A, D> MyTrait<A, D> for YourType where
17 A: TraitB + TraitC,
18 D: TraitE + TraitF {}
19 ```
20
21 * When using a `where` clause is more expressive than using normal syntax.
22 The `impl` in this example cannot be directly expressed without a `where` clause:
23
24 ```rust,editable
25 use std::fmt::Debug;
26
27 trait PrintInOption {
28 fn print_in_option(self);
29 }
30
31 // Because we would otherwise have to express this as `T: Debug` or
32 // use another method of indirect approach, this requires a `where` clause:
33 impl<T> PrintInOption for T where
34 Option<T>: Debug {
35 // We want `Option<T>: Debug` as our bound because that is what's
36 // being printed. Doing otherwise would be using the wrong bound.
37 fn print_in_option(self) {
38 println!("{:?}", Some(self));
39 }
40 }
41
42 fn main() {
43 let vec = vec![1, 2, 3];
44
45 vec.print_in_option();
46 }
47 ```
48
49 ### See also:
50
51 [RFC][where], [`struct`][struct], and [`trait`][trait]
52
53 [struct]: ../custom_types/structs.md
54 [trait]: ../trait.md
55 [where]: https://github.com/rust-lang/rfcs/blob/master/text/0135-where.md