Skip to content

Commit 7b5c3d2

Browse files
committed
Auto merge of #41857 - dhardy:master, r=steveklabnik
loop_break_value: add documentation for book Some notes at the top of the file. r? @steveklabnik
2 parents 2b6ed3a + 7ab35b7 commit 7b5c3d2

File tree

1 file changed

+73
-0
lines changed

1 file changed

+73
-0
lines changed

src/doc/unstable-book/src/language-features/loop-break-value.md

+73
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,80 @@ The tracking issue for this feature is: [#37339]
44

55
[#37339]: https://github.com/rust-lang/rust/issues/37339
66

7+
Documentation to be appended to section G of the book.
8+
79
------------------------
810

11+
### Loops as expressions
12+
13+
Like most things in Rust, loops are expressions, and have a value; normally `()` unless the loop
14+
never exits.
15+
A `loop` can instead evaluate to a useful value via *break with value*:
16+
17+
```rust
18+
#![feature(loop_break_value)]
19+
20+
// Find the first square number over 1000:
21+
let mut n = 1;
22+
let square = loop {
23+
if n * n > 1000 {
24+
break n * n;
25+
}
26+
n += 1;
27+
};
28+
```
29+
30+
The evaluation type may be specified externally:
31+
32+
```rust
33+
#![feature(loop_break_value)]
34+
35+
// Declare that value returned is unsigned 64-bit:
36+
let n: u64 = loop {
37+
break 1;
38+
};
39+
```
40+
41+
It is an error if types do not agree, either between a "break" value and an external requirement,
42+
or between multiple "break" values:
43+
44+
```no_compile
45+
#![feature(loop_break_value)]
46+
47+
loop {
48+
if true {
49+
break 1u32;
50+
} else {
51+
break 0u8; // error: types do not agree
52+
}
53+
};
54+
55+
let n: i32 = loop {
56+
break 0u32; // error: type does not agree with external requirement
57+
};
58+
```
59+
60+
#### Break: label, value
61+
62+
Four forms of `break` are available, where EXPR is some expression which evaluates to a value:
63+
64+
1. `break;`
65+
2. `break 'label;`
66+
3. `break EXPR;`
67+
4. `break 'label EXPR;`
68+
69+
When no value is given, the value `()` is assumed, thus `break;` is equivalent to `break ();`.
70+
71+
Using a label allows returning a value from an inner loop:
972

73+
```rust
74+
#![feature(loop_break_value)]
1075

76+
let result = 'outer: loop {
77+
for n in 1..10 {
78+
if n > 4 {
79+
break 'outer n;
80+
}
81+
}
82+
};
83+
```

0 commit comments

Comments
 (0)