Course contentsShow
← Rust
Lesson 46 of 1,9101. Rust Fundamentals and ToolingFree lesson

Control Flow Logic

Manage execution paths using loops, conditionals, and range-based iterators.

In this lesson, you will learn how to direct the execution of your program by making decisions and repeating tasks using if, loop, and range-based iterators.

Making Decisions with if

In Rust, the if statement allows your program to choose between paths. Because Rust is an expression-based language, you can even use an if block as the right-hand side of a variable assignment.

let number = 7;
let result = if number > 5 { "High" } else { "Low" };

Note: Both branches must return the same type, or the compiler will stop you!

Repeating Actions with loop

When you need to repeat a block of code, the simplest tool is loop. Unlike other languages, a loop in Rust continues indefinitely until you explicitly tell it to break. You can even return a value from a loop by placing it after the break keyword.

let mut counter = 0;
let final_value = loop {
    counter += 1;
    if counter == 3 {
        break counter * 2; // Returns 6
    }
};

Iterating with Ranges

While loop is great for indefinite tasks, we often want to perform an action a specific number of times. Rust provides ranges (like 0..5) to create iterators. Using a for loop with a range is the idiomatic way to handle repetitive logic safely.

// This will print 0, 1, 2, 3, 4
for i in 0..5 {
    println!("Current count: {}", i);
}

Why This Matters

Control flow is how your code handles state changes and conditions. By combining these structures with the pattern matching you learned previously, you can create complex logic while the compiler ensures that your branches are exhaustive and your loops are memory-safe. Remember, because these are expressions, they help keep your data flow clean and predictable—a core tenet of Rust’s safety guarantees.

Key Takeaway: Use if for conditional branching, loop for indefinite repetition, and range-based for loops for predictable iteration to maintain safe, readable execution paths.