In programming, loops are essential for executing a block of code repeatedly until a certain condition is met. Rust provides several types of loops to handle different scenarios, including for loops and while loops. Additionally, Rust supports loop labels, which can be used to break out of nested loops.
This tutorial will cover the basics of using loops in Rust, including how to use for loops, while loops, and how to control loops with labels.
A for loop is used when you know the number of iterations in advance. It iterates over a range or an iterator. The syntax for a for loop in Rust is as follows:
for variable in expression {
// code block to be executed repeatedly
}
The `expression` can be a range, an array, a vector, or any other iterable type.
### While Loops
A `while` loop continues executing as long as the specified condition evaluates to true. The syntax for a `while` loop is:
```rust
while condition {
// code block to be executed repeatedly
}
The `condition` must evaluate to a boolean value.
### Loop Labels
Loop labels are used to break out of nested loops or continue from an outer loop. A label is specified before the loop keyword and can be referenced within the loop body using the `break` or `continue` statements.
```rust
'outer: for i in 0..5 {
'inner: for j in 0..5 {
if i == 2 && j == 2 {
break 'outer;
}
println!("i = {}, j = {}", i, j);
}
}
In this example, the `break 'outer;` statement breaks out of both the inner and outer loops when `i` equals 2 and `j` equals 2.
## Examples
### For Loop Example
Here's an example of a `for` loop that iterates over a range from 0 to 4:
```rust
fn main() {
for i in 0..5 {
println!("Number: {}", i);
}
}
Number: 0 Number: 1 Number: 2 Number: 3 Number: 4
Here's an example of a while loop that continues until the condition is false:
fn main() {
let mut count = 0;
while count < 5 {
println!("Count: {}", count);
count += 1;
}
}
Count: 0 Count: 1 Count: 2 Count: 3 Count: 4
Here's an example of using loop labels to control nested loops:
fn main() {
'outer: for i in 0..5 {
'inner: for j in 0..5 {
if i == 2 && j == 2 {
break 'outer;
}
println!("i = {}, j = {}", i, j);
}
}
}
i = 0, j = 0 i = 0, j = 1 i = 0, j = 2 i = 0, j = 3 i = 0, j = 4 i = 1, j = 0 i = 1, j = 1 i = 1, j = 2 i = 1, j = 3 i = 1, j = 4 i = 2, j = 0 i = 2, j = 1
In the next section, we will explore functions in Rust. Functions are a fundamental building block of any programming language and allow you to encapsulate reusable code.
Stay tuned!