Lesson 5 of 20

Control Flow

Control Flow in Rust

if/else as an Expression

Unlike most languages, if/else in Rust is an expression — it returns a value:

let number = 7;
let description = if number > 5 { "big" } else { "small" };
println!("{}", description); // big

loop

loop runs forever until you break:

let mut counter = 0;
let result = loop {
    counter += 1;
    if counter == 10 {
        break counter * 2; // break can return a value
    }
};

while

let mut n = 1;
while n < 100 {
    n *= 2;
}

for with ranges

for i in 0..5 {       // 0, 1, 2, 3, 4 (exclusive end)
    print!("{} ", i);
}
for i in 0..=5 {      // 0, 1, 2, 3, 4, 5 (inclusive end)
    print!("{} ", i);
}

match

match is Rust's powerful pattern matching construct. Like if, it's an expression:

let x = 3;
let msg = match x {
    1 => "one",
    2 | 3 => "two or three",
    4..=10 => "four to ten",
    _ => "something else",
};

Your Task

Implement three functions:

  1. fizzbuzz(n: u32) -> String — returns "FizzBuzz" if divisible by both 3 and 5, "Fizz" if by 3, "Buzz" if by 5, otherwise the number as a string. Use match.
  2. sum_range(start: u32, end: u32) -> u32 — returns the sum of all integers from start to end inclusive.
  3. collatz_steps(n: u64) -> u32 — counts how many steps to reach 1 in the Collatz sequence: if n is even, divide by 2; if odd, multiply by 3 and add 1.
Rust (Miri) loading...
Loading...
Click "Run" to execute your code.