Skip to content

Commit f478df7

Browse files
Merge pull request #699 from pietroalbini/loop_break_value
Document the loop_break_value feature
2 parents 5ee93a0 + 38cb0d7 commit f478df7

File tree

1 file changed

+25
-1
lines changed

1 file changed

+25
-1
lines changed

second-edition/src/appendix-07-newest-features.md

+25-1
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,31 @@ fn main() {
2929

3030
// Using field init shorthand:
3131
let portia = Person { name, age };
32-
32+
3333
println!("{:?}", portia);
3434
}
3535
```
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+
```

0 commit comments

Comments
 (0)