Rust Essential Course – Lesson 4

Lesson 4: Control Flow in Rust

Introduction

Control flow allows your program to make decisions and repeat actions. In Rust, you use familiar constructs like ifelse ifelse, and looping with loopwhile, and for. This makes your code dynamic and powerful.

Conditional Statements (ifelse ifelse)

Rust’s if statement works much like other languages but with an emphasis on type safety—conditions must always be boolean.

fn main() {
    let number = 7;

    if number < 10 {
        println!("Small number!");
    } else if number < 100 {
        println!("Medium-sized number!");
    } else {
        println!("Big number!");
    }
}
  • The code block after the first if runs if number < 10.
  • If that’s false but number < 100 is true, the else if block runs.
  • Otherwise, the else block is executed.

Using if as an Expression

Rust allows if expressions to assign values:

fn main() {
    let is_even = if number % 2 == 0 { true } else { false };
    println!("Is even? {}", is_even);
}

Looping with loopwhile, and for

1. The Infinite loop

loop runs forever unless you explicitly break out of it.

fn main() {
    let mut count = 0;
    loop {
        println!("Count: {}", count);
        count += 1;
        if count >= 5 {
            break; // exit the loop
        }
    }
}

2. Conditional Looping with while

while keeps looping as long as its condition is true.

fn main() {
    let mut n = 3;
    while n > 0 {
        println!("{}!", n);
        n -= 1;
    }
    println!("Liftoff!");
}

3. Iterating with for

for loops are best for iterating over ranges or collections.

fn main() {
    for i in 1..=5 {
        println!("Number: {}", i);
    }
}
  • 1..=5 means from 1 to 5, inclusive.

Interactive Task 1: FizzBuzz Mini-Exercise

Try this classic coding challenge:

  • Print numbers from 1 to 15.
  • For multiples of 3, print Fizz instead of the number.
  • For multiples of 5, print Buzz.
  • For numbers divisible by both, print FizzBuzz.
fn main() {
    // Your FizzBuzz code here!
}

Tip: Use a for loop with if-else statements inside.

Solution: https://gist.github.com/rust-play/c4a104c212dc94ef5f885d96513e9ea3

Mini-Challenge

Write a program that counts down from 10 to 1 using a while loop and prints “Blast off!” at the end.

Solution: https://gist.github.com/rust-play/c92404da3c456fdd3761f0287f85928f

Recap

  • Use ifelse if, and else for decisions.
  • Use loop for infinite or manual-exit repetition, while for condition-based repetition, and for for range or collection iteration.
  • Rust’s control flow features are type-safe and expressive.

Did you complete the tasks? Share your FizzBuzz or countdown code in the comments! Have questions about if or loops? Let’s discuss!

Go to Course Structure or Navigate to next blog!

Leave a Comment

Your email address will not be published. Required fields are marked *