]>
Commit | Line | Data |
---|---|---|
cc61c64b XL |
1 | # Appendix G - Newest Features |
2 | ||
3 | This appendix documents features that have been added to stable Rust since the | |
4 | main part of the book was completed. | |
5 | ||
6 | ||
7 | ## Field init shorthand | |
8 | ||
9 | We can initialize a data structure (struct, enum, union) with named | |
10 | fields, by writing `fieldname` as a shorthand for `fieldname: fieldname`. | |
11 | This allows a compact syntax for initialization, with less duplication: | |
12 | ||
13 | ```rust | |
14 | #[derive(Debug)] | |
15 | struct Person { | |
16 | name: String, | |
17 | age: u8, | |
18 | } | |
19 | ||
20 | fn main() { | |
21 | let name = String::from("Peter"); | |
22 | let age = 27; | |
23 | ||
24 | // Using full syntax: | |
25 | let peter = Person { name: name, age: age }; | |
26 | ||
27 | let name = String::from("Portia"); | |
28 | let age = 27; | |
29 | ||
30 | // Using field init shorthand: | |
31 | let portia = Person { name, age }; | |
7cac9316 | 32 | |
cc61c64b XL |
33 | println!("{:?}", portia); |
34 | } | |
35 | ``` | |
7cac9316 XL |
36 | |
37 | ||
38 | ## Returning from loops | |
39 | ||
40 | One of the uses of a `loop` is to retry an operation you know can fail, such as | |
41 | checking if a thread completed its job. However, you might need to pass the | |
42 | result of that operation to the rest of your code. If you add it to the `break` | |
43 | expression you use to stop the loop, it will be returned by the broken loop: | |
44 | ||
45 | ```rust | |
46 | fn main() { | |
47 | let mut counter = 0; | |
48 | ||
49 | let result = loop { | |
50 | counter += 1; | |
51 | ||
52 | if counter == 10 { | |
53 | break counter * 2; | |
54 | } | |
55 | }; | |
56 | ||
57 | assert_eq!(result, 20); | |
58 | } | |
59 | ``` |