1
0
mirror of https://github.com/google/comprehensive-rust.git synced 2025-06-15 05:40:30 +02:00
Files
comprehensive-rust/src/control-flow-basics/break-continue.md
Lalit Shankar Chowdhury 45f869902b Clarify and fix grammatical errors (#2347)
Fix minor grammatical errors in Day 1: Morning.

Speaker notes 6.5: "the `-> ()` return type" changed to "the return
type".

The compiler will infer the unit type for any type omitted.
2024-09-04 18:54:14 +00:00

922 B

minutes
minutes
4

break and continue

If you want to immediately start the next iteration use continue.

If you want to exit any kind of loop early, use break. With loop, this can take an optional expression that becomes the value of the loop expression.

fn main() {
    let mut i = 0;
    loop {
        i += 1;
        if i > 5 {
            break;
        }
        if i % 2 == 0 {
            continue;
        }
        println!("{}", i);
    }
}

Note that loop is the only looping construct which can return 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).