Rust loop
Created By: chatGPT
Looping in Rust is a fundamental concept that allows you to execute a block of code repeatedly. Rust provides several types of loops, including
loop
, while
, and for
loops. Each type serves different scenarios depending on the requirements of your program.fn main() {
// Infinite loop using `loop`
let mut count = 0;
loop {
count += 1;
println!("Count: {}", count);
if count >= 5 {
break;
}
}
}
While loops in Rust continue executing as long as a specified condition remains
true
. This type of loop is useful when the number of iterations is not known beforehand and relies on a dynamic condition.fn main() {
let mut number = 0;
while number < 5 {
println!("Number: {}", number);
number += 1;
}
}
For loops are particularly handy when you need to iterate over a collection or a range of numbers. It simplifies the syntax and handles initialization and incrementing automatically.
fn main() {
for number in 0..5 {
println!("Number: {}", number);
}
}
You can also combine loops with other control flow structures like
if
to create more complex behaviors. The following example demonstrates using an if
statement inside a for
loop to print only even numbers.fn main() {
for number in 0..10 {
if number % 2 == 0 {
println!("Even number: {}", number);
}
}
}