Rust loop

ww‮.w‬theitroad.com

In Rust, you can use loops to execute a block of code repeatedly until a certain condition is met. There are several types of loops available in Rust:

  1. loop: This loop will run indefinitely until it is explicitly terminated by a break statement. Here's an example:
loop {
    println!("This will be printed repeatedly");
    break; // This will terminate the loop after the first iteration
}
  1. while: This loop will execute the block of code as long as the specified condition is true. Here's an example:
let mut x = 0;
while x < 10 {
    println!("x is {}", x);
    x += 1;
}

In this example, the loop will execute as long as x is less than 10. The loop will print the value of x, increment it by 1, and repeat until x is no longer less than 10.

  1. for: This loop is used to iterate over collections such as arrays, ranges, or iterators. Here's an example:
let arr = [1, 2, 3, 4, 5];
for i in arr.iter() {
    println!("{}", i);
}

In this example, the loop will iterate over each element of the arr array and print its value.

You can also use the break and continue statements within loops to control their behavior. The break statement will immediately terminate the loop, while the continue statement will skip the current iteration and move on to the next one.