]>
Commit | Line | Data |
---|---|---|
532ac7d7 XL |
1 | Please add this text at the end of the Function Pointers section, just before |
2 | the Returning Closures section starts, so at the end of page 447 and before | |
3 | page 448. | |
4 | ||
5 | --- | |
6 | ||
7 | We have another useful pattern that exploits an implementation detail of tuple | |
8 | structs and tuple-struct enum variants. These types use `()` as initializer | |
9 | syntax, which looks like a function call. The initializers are actually | |
10 | implemented as functions returning an instance that’s constructed from their | |
11 | arguments. We can use these initializer functions as function pointers that | |
12 | implement the closure traits, which means we can specify the initializer | |
13 | functions as arguments for methods that take closures, like so: | |
14 | ||
15 | ``` | |
16 | enum Status { | |
17 | Value(u32), | |
18 | Stop, | |
19 | } | |
20 | ||
21 | let list_of_statuses: Vec<Status> = | |
22 | (0u32..20) | |
23 | .map(Status::Value) | |
24 | .collect(); | |
25 | ``` | |
26 | ||
27 | Here we create `Status::Value` instances using each `u32` value in the range | |
28 | that `map` is called on by using the initializer function of `Status::Value`. | |
29 | Some people prefer this style, and some people prefer to use closures. They | |
30 | compile to the same code, so use whichever style is clearer to you. | |
31 |