1
0
mirror of https://github.com/google/comprehensive-rust.git synced 2025-12-22 22:51:12 +02:00
Files
comprehensive-rust/src/control-flow-basics/break-continue.md
Eric Githinji 0daab179e9 Use dbg! instead of println! in Day 1 mng session (#2652)
As mentioned in #2478, this cleans up the code blocks when all that is
needed is a trivial debug print statement.
Only making changes to Day 1 morning session so that I can get feedback
before proceeding with the rest of the course.

---------

Co-authored-by: Eric Githinji <egithinji@google.com>
2025-02-24 14:12:56 +00:00

912 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;
        }
        dbg!(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).