Loops are like the one thing that defines a programming language. They are an essential construct that provides the ability to continuously execute an action as long as a condition is true.
This article will discuss how we can implement and use loop constructs in the Rust programming language.
Rust Loop Constructs
Rust provides us with the following looping constructs
- A for loop
- While loop
- A loop
Let us explore how each construct works and how to use it.
Rust For Loop
A for loop in Rust is used to iterate over elements of an iterable object using an Iterator. It returns a series of values until the iterator is empty. The value from the for loop can then be used to perform an action inside the loop body.
The syntax for a for loop in Rust is as shown:
//do
}
Example usage of a for loop is to iterate over the elements of an array. An example is as shown below:
letarr:[i32; 3] = [10,20,30];
for item inarr {
println!("{}", item);
}
}
Another example of the for loop is to iterate over a range of integers using the keyword. For example:
foriin1..10 {
println!("{}", i);
}
}
The above example iterates over the elements from 1 to 10, exclusive of the last element. If you want to include 10 in the values, use the syntax:
println!("{}", i);
}
Rust While Loop
The while loop executes a block of code until the specified condition is false. Hence, as long as a condition is true, the block inside the whole body will run continuously.
An example is as shown:
letmuti = 0;
whilei<= 5 {
println!("{}", i);
i += 1;
}
}
For the code above, we start by defining a mutable variable i. We then use a while loop to continuously execute a block of code while the value of i is less than or equal to 5.
Keep in mind that we update the value of i on every iteration to prevent an infinite loop.
Rust Loop
The loop expression in rust, denoted by the loop keyword, shows an infinite loop. This loop construct uses the break and continues keywords to exit and skip an iteration.
An example is as shown:
letmuti = 0u32;
loop {
i += 1;
ifi == 5 {
println!("{}", i);
continue;
}
ifi == 10 {
println!("{}", i);
break;
}
}
}
The code above will run infinitely until it counters the break statement.
Conclusion
This article explores various looping constructs in the Rust programming language. Using this article, you are in a position to tackle looping needs in your Rust programs.
We hope you enjoyed the article and thanks for reading it!