summaryrefslogtreecommitdiff
path: root/Returning values from loops.md
blob: 7f0b1165f4970cc3a7f9f79179d33a7e2e46fc89 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
[[Rust]]
[[A scope block is an expression]]
[[Loop labels]]


A loop can return values, it is an expression. Thus it can be used in an assignment as well.
It is possible to `return ` but that would exit the function, instead we can also `break expression;` and return a value just from the loop by breaking it with a value (as we would normally write a `return`).

```rust
fn main() {
    let mut counter = 0;

    let result = loop {
        counter += 1;

        if counter == 10 {
            break counter * 2;
        }
    };

    println!("The result is {result}");
}
```