Skip to content

Control Flow

If/Else

rust
let num = 5;
if num < 3 {
    println!("Less than 3");
} else if num <= 3 && num < 7 {
    println!("In the sweet spot");
} else {
    println!("Greater!");
}

With Options and Results

rust
let config_max = Some(3u8);
if let Some(max) = config_max {
    println!("The maximum is configured to be {}", max);
}

Loops

Loop

The loop keyword is essentially a while(true) loop, it continues to execute the block until you explicitly tell it to stop.

You can also return values from loops by using break followed by the return value, and setting that equal to a variable.

rust
loop {
    println!("again!");
}

let mut counter = 0;

let result = loop {
    counter += 1;

    if counter == 10 {
        break counter * 2;
    }
};

println!("The result is {result}");

While loops

Pretty much the same as while loops in any other language.

rust
 let mut number = 3;

while number != 0 {
    println!("{number}!");

    number -= 1;
}

println!("LIFTOFF!!!");

For loops

For loops in Rust are always for in loops.

rust
let a = [10, 20, 30, 40, 50];

for element in a {
    println!("the value is: {element}");
}

for number in (1..4).rev() {
    println!("{number}!");
}
println!("LIFTOFF!!!");

Match

rust
enum Coin {
    Penny,
    Nickel,
    Dime,
    Quarter(UsState),
}

fn value_in_cents(coin: Coin) -> u8 {
    match coin {
        Coin::Penny => 1,
        Coin::Nickel => 5,
        Coin::Dime => 10,
        Coin::Quarter(state) => {
            println!("State quarter from {:?}!", state);
            25
        },
        _ => {
            println("Other!")
        }
    }
}

fn plus_one(x: Option<i32>) -> Option<i32> {
        match x {
            None => None,
            Some(i) => Some(i + 1),
        }
    }