create a forlopp with an if statement in rust

We can create a for loop with an if statement in Rust. Here is an example:

main.rs
fn main() {
    let v = vec![1, 2, 3, 4, 5];

    for i in v {
        if i % 2 == 0 {
            println!("{} is even", i);
        } else {
            println!("{} is odd", i);
        }
    }
}
199 chars
12 lines

In this example, we define a vector v of integers and loop over them using a for loop. Inside the loop, we have an if statement that checks whether the current integer is even or odd. If it is even, we print "X is even", otherwise we print "X is odd".

Note that the for i in v line loops over the elements of the vector, rather than the indices like in other programming languages.

related categories

gistlibby LogSnag