Rust Control Statements (break & continue) Tutorial

In this Rust tutorial we learn how to use the break and continue control statements to control the flow of our loops with conditional expressions such as the if statement.

Here's a table of contents of what you'll learn in this lesson:
(click on a link to skip to its section)

Let's jump right in.

What are control statements

Control statements allow us to control the flow of our for and while loops in our Rust application.

Rust provides us with two loop control statements, namely:

  • break
  • continue

As we’ll see, the break and continue control statements are often used with conditional expressions like the if statement.

The break control statement

The break control statement allows us to stop the execution of a loop, break out of its iteration cycle and continue on to any code after it.

To use the break control statement, we simply write the break keyword where we want to break out of the loop.

Example: break out of a loop
fn main() {

    for x in 0..10 {

        if x == 5 {
            break;
        }

    	println!("{}", x);
    }

}

In the example above, we break out of the loop when the number reaches 5.

The compiler will completely stop any further iterations of the loop and move on to code after it.

The continue control statement

We use the continue control statement to skip to the next iteration of the loop.

When the compiler encounters the continue keyword, it will stop executing code in the rest of the code block and skip to the next iteration of the loop.

Example:
fn main() {

    for x in 0..10 {

        if x == 5 {
            continue;
        }

    	println!("{}", x);
    }

}

In the example above, we skip to the next iteration of the loop when the number reaches 5.

Because the compiler skipped the rest of the code in the block when it reached 5, it didn’t print to the console.

The compiler then moved on to the next iteration (6) and executed the println normally so we see the rest of the numbers in the console.

Summary: Points to remember

  • Loop control statements allow us to control the flow of our for and while loops in Rust.
  • Loop control statements are often used with conditional expressions such as the if statement.
  • The break control statement stops execution of the loop completely and moves on to any code below it.
  • The continue control statement skips the rest of the code for that iteration and moves on to the next iteration.