create a loop in rust

In Rust, we can create loops using the loop keyword. The loop keyword creates an infinite loop, which means the loop will continue to run until we explicitly tell it to stop.

Here's an example of a basic loop in Rust:

main.rs
// a basic loop in rust
loop {
    println!("infinite loop!");
}
65 chars
5 lines

The loop above will run continuously, printing "infinite loop!" to the console.

We can also add some control flow to our loop by using keywords like break and continue. break will break out of the loop entirely, while continue will skip the current iteration and move on to the next.

main.rs
// a loop with control flow in rust
let mut i = 0;
loop {
    if i == 5 {
        break; // break out of the loop when i equals 5
    }
    if i % 2 == 0 {
        i += 1;
        continue; // skip this iteration when i is even
    }
    println!("{}", i);
    i += 1;
}
271 chars
14 lines

In the example above, the loop will run until i equals 5. When i is even, we use the continue keyword to skip that iteration of the loop. When i is odd, we print its value to the console and increment i by 1.

Loops are an important part of any programming language. Rust's loop keyword provides a flexible and easy-to-use way to create loops and add control flow to them.

gistlibby LogSnag