Rust Learning Plan – Day 3 Basic Operations and Control Flow

Today’s topic is: Control Flow — enabling your program to make choices, loop, and have logic. Rust’s control flow is similar to Python but is stricter and safer.

Day 3 Learning Plan (approximately 1–2 hours)

Learning Objectives

  • • Master <span>if</span>, <span>else if</span>, and <span>else</span>
  • • Understand the three types of loops: <span>loop</span>, <span>while</span>, and <span>for</span>
  • • Know the functions of <span>break</span> and <span>continue</span>

Task Arrangement

1. if Expression (20 minutes)

  • • In Rust, <span>if</span> is an expression that can directly return a value.
    fn main() {
        let x = 7;
        if x < 5 {
            println!("x is less than 5");
        } else if x == 5 {
            println!("x is equal to 5");
        } else {
            println!("x is greater than 5");
        }
    
        // if as an expression
        let result = if x % 2 == 0 { "even" } else { "odd" };
        println!("x is {}", result);
    }

    Unlike Python, the condition of <span>if</span> must be of type <span>bool</span> and cannot be automatically converted.

2. Three Types of Loops (40 minutes)

loop (similar to Python’s while True)

let mut counter = 0;
loop {
    counter += 1;
    println!("counter = {}", counter);
    if counter == 3 {
        break;
    }
}

while Loop

let mut n = 5;
while n > 0 {
    println!("Countdown: {}", n);
    n -= 1;
}
println!("Launch!");

for Loop

let arr = [10, 20, 30, 40];
for value in arr {
    println!("value = {}", value);
}

// Iterating over a range
for i in 1..=5 {
    println!("Iteration {}", i);
}

3. break and continue (10 minutes)

for i in 1..10 {
    if i == 3 {
        continue; // skip 3
    }
    if i == 8 {
        break; // exit loop early
    }
    println!("i = {}", i);
}

4. Today’s Exercise (20 minutes) Write a small program to print numbers from 1 to 100:

  • • Output “Fizz” for numbers divisible by 3
  • • Output “Buzz” for numbers divisible by 5
  • • Output “FizzBuzz” for numbers divisible by both 3 and 5
  • • Output the number itself for others

Example:

1
2
Fizz
4
Buzz
...

This is a classic problem that also practices the combination of <span>if</span>, <span>for</span>, and <span>println!</span>.

Day 3 Summary

Today you have learned to make your program “think” and “loop.” Rust’s control structures are concise, and due to its strict type system, it almost eliminates implicit logical errors.

Next, on Day 4, we will officially enter Functions and Code Structure — learning about function definitions, parameters, return values, scope, and how to break logic into modules.

Leave a Comment