2023-11-29 10:39:24 -05:00
|
|
|
---
|
2024-02-06 15:48:56 -05:00
|
|
|
minutes: 4
|
2023-11-29 10:39:24 -05:00
|
|
|
---
|
|
|
|
|
|
|
|
# `break` and `continue`
|
|
|
|
|
2024-02-16 03:49:06 +05:30
|
|
|
If you want to immediately start the next iteration use
|
|
|
|
[`continue`](https://doc.rust-lang.org/reference/expressions/loop-expr.html#continue-expressions).
|
|
|
|
|
2023-11-29 10:39:24 -05:00
|
|
|
If you want to exit any kind of loop early, use
|
|
|
|
[`break`](https://doc.rust-lang.org/reference/expressions/loop-expr.html#break-expressions).
|
2024-08-13 14:27:08 +00:00
|
|
|
With `loop`, this can take an optional expression that becomes the value of the
|
2023-12-31 00:15:07 +01:00
|
|
|
`loop` expression.
|
2023-11-29 10:39:24 -05:00
|
|
|
|
|
|
|
```rust,editable
|
|
|
|
fn main() {
|
2024-02-16 03:49:06 +05:30
|
|
|
let mut i = 0;
|
|
|
|
loop {
|
|
|
|
i += 1;
|
|
|
|
if i > 5 {
|
|
|
|
break;
|
2023-11-29 10:39:24 -05:00
|
|
|
}
|
2024-02-16 03:49:06 +05:30
|
|
|
if i % 2 == 0 {
|
|
|
|
continue;
|
2023-11-29 10:39:24 -05:00
|
|
|
}
|
2024-02-16 03:49:06 +05:30
|
|
|
println!("{}", i);
|
2023-11-29 10:39:24 -05:00
|
|
|
}
|
|
|
|
}
|
|
|
|
```
|
2024-08-21 16:33:50 +10:00
|
|
|
|
|
|
|
<details>
|
|
|
|
|
|
|
|
Note that `loop` is the only looping construct which can returns a non-trivial
|
|
|
|
value. This is because it's guaranteed to only return at a `break` statement
|
|
|
|
(unlike `while` and `for` loops, which can also return when the condition
|
|
|
|
fails).
|
|
|
|
|
|
|
|
</details>
|