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);
let age: Result<u8, _> = "34".parse();
if let Some(max) = config_max {
    println!("The maximum is configured to be {}", max);
} else if let Ok(age) = age {
    println!("Age is {}", age);
}

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),
    }
}

// Or
let x = 1;
match x {
    1 | 2 => println!("one or two"),
    3 => println!("three"),
    _ => println!("anything"),
}

// Range
let x = 5;
match x {
    1..=5 => println!("one through five"),
    _ => println!("something else"),
}