Rust Tutorials: Understanding `break` and `continue`

beginner
19 min

Rust Tutorials: Understanding break and continue

Welcome to our comprehensive guide on the break and continue keywords in Rust! These powerful tools can help you control the flow of your loops, making your code more efficient and easier to manage. Let's dive in!

What are break and continue?

break and continue are control flow statements that allow you to manipulate loops in Rust. They are essential for writing clean and effective code.

šŸ’” Pro Tip: break terminates a loop, while continue skips the current iteration and moves on to the next one.

The break Statement

The break keyword is used to terminate a loop early. Once the break statement is executed, the loop will immediately stop, and the program continues with the next statement following the loop.

rust
fn main() { for i in 0..10 { if i == 5 { println!("Breaking at {}", i); break; } println!("Iteration {}", i); } println!("Loop finished."); }

In the example above, we're using a for loop to iterate over numbers from 0 to 9. When we reach the number 5, we use the break statement to terminate the loop, and the program prints "Loop finished."

The continue Statement

The continue keyword is used to skip the current iteration of a loop and move on to the next one.

rust
fn main() { for i in 0..10 { if i % 2 == 0 { println!("Skipping even number: {}", i); continue; } println!("Iteration {}", i); } println!("Loop finished."); }

In this example, we're using a for loop to iterate over numbers from 0 to 9. If the number is even, we use the continue statement to skip that iteration and move on to the next one. The program prints only odd numbers.

Quiz Time!

Quick Quiz
Question 1 of 1

What does the `break` statement do in Rust?

Quick Quiz
Question 1 of 1

What does the `continue` statement do in Rust?

That's it for this tutorial! With break and continue, you're well on your way to mastering Rust's control flow statements. In the next lesson, we'll delve deeper into Rust's loop structures and explore more ways to manage your code effectively. Happy coding! šŸŽÆ šŸ“ āœ