Control Flow

if, loop, while, and for

If Statements

If you've been using Java, if statements in Rust will look really familiar, with just a few less parentheses.

main.rs

fn main() {
    let number = 3;
    
    if number < 5 {
        println!("number isn't very big");
    } else if > 9 {
        println!("oh wow that is big");
    } else {
        println!("i guess it's somewhere in the middle");
    }
}

The expression to the right of the if must evaluate to a boolean. Rust does not convert non-boolean types to boolean values (unlike a language like Ruby).

You can also use if on the right side of a let statement:

main.rs
fn main() {
    let condition = true;
    let number = if condition {
        5

    } else {
        6
    };

    println!("The value of number is: {}", number);
}

One key thing: the results must be of the same type. So while the above works, this doesn't:

Loops

Rust has three types of loops: loop, while, and for. Let's try them all!

Loop

We looked into this basic type of loop during Guessing Game. As a refresher, this is what a basic loop looks like:

Caveat: if you run this, it will just print again! over and over again. Make sure to use break; within a condition to leave the loops and avoid an endless loop!

While (Conditional Loops)

More often, you are likely to use a while loop. Instead of using loop and if, you can just use a single while like this:

This loop will loop three times until number is zero. At that point, it will break out of the loop and print out the next line. This is equivalent to:

For

While you can loop through a collection with a while loop like this:

It's a little bulky though. Let's do the same thing with a for loop:

Instead of having to parse out what the index is doing (and having to define it), the for loop allows us to write code that's a little closer to English:

for element in array do this { statement }

We can also redo that countdown with a for loop and make it even more clear and concise:

Last updated