Lesson 04

Control Flow

Make decisions with if, match, loop, while, and for.

Learning objectives

If Expressions

Rust uses if expressions to run different blocks of code based on conditions. Conditions must evaluate to a boolean value.

Match Expressions

The match expression is one of Rust’s most useful control flow tools. It allows you to compare a value against multiple patterns in a clear and safe way.

Loops

Rust provides loop, while, and for. For most beginner programs, for loops are very useful when working with ranges or collections.

Example code

fn main() {
    let mark = 82;

    if mark >= 50 {
        println!("Pass");
    } else {
        println!("Fail");
    }

    let grade = match mark {
        90..=100 => "A",
        80..=89 => "B",
        70..=79 => "C",
        50..=69 => "D",
        _ => "F",
    };

    println!("Grade: {}", grade);

    for number in 1..=5 {
        println!("Number: {}", number);
    }
}
Practice task: Write a program that checks a temperature and prints “Cold”, “Warm”, or “Hot”.