<tutorialjinni.com/>

Rust Loops

Posted Under: Programming, Rust, Rust Tutorial For Beginners, Tutorials on Sep 28, 2021
Rust Loops
Loops is a way to execute a portion of code again and again to meet a certain objective. Rust provides different looping functionalities for different situations and settings. Loops in Rust appear to be different for programmers with a background in JAVA, or PHP.

For Loop in Rust

fn main() {
    for i in 1..=5 {
        println!("Value of I is {}",i);
    }
}
This will print Value of I 1 through 5, = says print value of i until i is less than or equal to 5. If = is not specified then 1 -> 4 values are printed. For loop range can be defined as
1..5;   // 1 through 5 excluding 5
5..;    // From 5 and onward
..6;    // Till 5, but excluding 6
..;     // Continuous Loop
1..=6;  // 1 to 6 including 6
..=7;   // start to 7 including 7

Rust Loop Array

Another way to Iterate through all values in array is as following, notice the _key variable prints the index of the array.
fn main() {
    let mut arr =[9,8,7,6,5,4,3,2,1];
    for (_key,_value) in  arr.iter_mut().enumerate(){
        println!("Array Key:{} Array Value:{}",_key,_value);
    }
}

// Output
Array Key:0 Array Value:9
Array Key:1 Array Value:8
Array Key:2 Array Value:7
Array Key:3 Array Value:6
Array Key:4 Array Value:5
Array Key:5 Array Value:4
Array Key:6 Array Value:3
Array Key:7 Array Value:2
Array Key:8 Array Value:1

Rust for Loop with Step

You can also define steps or increments in for loop, to do that a special function step_by is used
fn main() {
    let mut i=0;
    for i in (1..20).step_by(i+2) {
        println!("{}", i); // Print odd Number only
    }
}

Rust while Loop

While loop iterate until a boolean condition is false. For demonstration, let's compute the sum of the first 100 even numbers.
fn main() {
    let mut even_sum=0;
    let mut i=1;

    while i <= 100 { // Loop until Condition is true
        if i % 2==0{
            even_sum=even_sum + i;
        }
        i=i+1;
    }
    println!("Sum is {}",even_sum);

}

Loop

Rust define a unique expression loop. It is basically a infinite loop.
fn main() {
    loop {
        println!("Loop till eternity");
    }
}


imgae