Rust loops: Difference between revisions

From wikinotes
No edit summary
No edit summary
Line 36: Line 36:
</syntaxhighlight>
</syntaxhighlight>
</blockquote><!-- loop -->
</blockquote><!-- loop -->
= while =
<blockquote>
<syntaxhighlight lang="rust">
let mut num = 0;
while num < 5 {
    index += 1;
}
</syntaxhighlight>
</blockquote><!-- while -->

Revision as of 14:49, 7 February 2023

General

Breaking/Continuing etc.

break;     // exit loop
continue;  // skip to next iteration of loop

Break can be assigned a return value

break 123  // return value '123' from loop

Loop Labels

Loops can be assigned labels, so that you can target which loop to break out of.

'outer_loop: loop {
    loop {
        break 'outer_loop;
    }
}


loop

loop {
    // loop forever
}

while

let mut num = 0;

while num < 5 {
    index += 1;
}