@@ -4,7 +4,89 @@ The tracking issue for this feature is: [#37339]
4
4
5
5
[ #37339 ] : https://github.com/rust-lang/rust/issues/37339
6
6
7
+ Documentation to be appended to section 3.6 of the book: Loops (after "Loop Labels", or before if
8
+ the "Break" section is moved). If this is deemed too complex a feature this early in the book, it
9
+ could also be moved to a new section (please advise). This would allow examples breaking with
10
+ non-primitive types, references, and discussion of coercion (probably unnecessary however).
11
+
7
12
------------------------
8
13
14
+ ### Loops as expressions
15
+
16
+ Like everything else in Rust, loops are expressions; for example, the following is perfectly legal,
17
+ if rather useless:
18
+
19
+ ``` rust
20
+ let result = for n in 1 .. 4 {
21
+ println! (" Hello, {}" , n );
22
+ };
23
+ assert_eq! (result , ());
24
+ ```
25
+
26
+ Until now, all the loops you have seen evaluate to either ` () ` or ` ! ` , the latter being special
27
+ syntax for "no value", meaning the loop never exits. A ` loop ` can instead evaluate to
28
+ a useful value via * break with value* :
29
+
30
+ ``` rust
31
+ // Find the first square number over 1000:
32
+ let mut n = 1 ;
33
+ let square = loop {
34
+ if n * n > 1000 {
35
+ break n * n ;
36
+ }
37
+ n += 1 ;
38
+ };
39
+ ```
40
+
41
+ The evaluation type may be specified externally:
42
+
43
+ ``` rust
44
+ // Declare that value returned is unsigned 64-bit:
45
+ let n : u64 = loop {
46
+ break 1 ;
47
+ };
48
+ ```
49
+
50
+ It is an error if types do not agree, either between a "break" value and an external requirement,
51
+ or between multiple "break" values:
52
+
53
+ ``` rust
54
+ loop {
55
+ if random_bool () {
56
+ break 1u32 ;
57
+ } else {
58
+ break 0u8 ; // error: types do not agree
59
+ }
60
+ };
61
+
62
+ let n : i32 = loop {
63
+ break 0u32 ; // error: type does not agree with external requirement
64
+ };
65
+ ```
66
+
67
+ For now, breaking with a value is only possible with ` loop ` ; the same functionality may
68
+ some day be added to ` for ` and ` while ` (this would require some new syntax like
69
+ ` while f() { break 1; } default { break 0; } ` ).
70
+
71
+ #### Break: label, value
72
+
73
+ Four forms of ` break ` are available, where EXPR is some expression which evaluates to a value:
74
+
75
+ 1 . ` break; `
76
+ 2 . ` break 'label; `
77
+ 3 . ` break EXPR; `
78
+ 4 . ` break 'label EXPR; `
79
+
80
+ When no value is given, the value ` () ` is assumed, thus ` break; ` is equivalent to ` break (); ` .
9
81
82
+ Using a label allows returning a value from an inner loop:
10
83
84
+ ``` rust
85
+ let result = 'outer : loop {
86
+ for n in 1 .. 10 {
87
+ if n > 4 {
88
+ break 'outer n ;
89
+ }
90
+ }
91
+ };
92
+ ```
0 commit comments