shlogg · Early preview
Jeff Mitchell @sentinel1909

Rust Loops: Loop, While, And For Explained

Learn how to control flow with loops in Rust: loop, while, and for. Master repetition of code until desired outcome or event.

Last time, in Decisions, Decisions, we looked at a method for adding logic within a program, via the if and if else expressions. Next up, we see how we can further control the flow, through loops. Loops allow repetition of blocks of code until some desired event or outcome. There are three kinds of loops in Rust: loop, while, and for.
Let's take a look at each one.

  
  
  loop

The loop keyword tells Rust to execute the same block of code over, and over, and over again, until told specifically to stop. Here’s a basic example:

fn main() {
    loop {
        println!("Help, I'm stuck in a loo...