Control Flow

Programming Languages · Rust Control Flow & Ownership · 12 min

Make decisions with if and else, and repeat code with loop, while and for.

if and else

if runs code only when a condition is true. else runs when it isn't. Add more choices in between with else if. No brackets needed around the condition:

if temp > 25 {
    println!("Hot");
} else {
    println!("Not hot");
}

Compare with >, <, >=, <=, == (equal) and != (not equal).

  • If age is 18 or more, print You can vote. Otherwise, print Not yet.

if gives back a value

In Rust, if is an expression, so it can produce a value you store with let. Both branches must give the same type:

let size = if n > 100 { "big" } else { "small" };

Handy tip: n % 2 is the remainder after dividing by 2. It's 0 for even numbers.

  • Create kind that is "even" if n % 2 == 0, else "odd".

  • Print 7 is odd using n and kind.

loop and break

loop repeats its block forever, until you say break:

loop {
    println!("again!");
    break; // stop after one go
}

Usually you break inside an if. Also new: count += 1 is a short way to write count = count + 1.

  • Write a loop that adds 1 to count, prints it, and stops with break once count is 3.

while

while checks a condition before each round, and stops as soon as it's false:

while fuel > 0 {
    fuel -= 1;
}

-= 1 takes one away, just like += 1 adds one.

  • Use while to count down: print n, then take 1 away, while n is above 0.

  • After the loop, print Liftoff!

for over a range

for walks through a range of numbers. 1..4 gives 1, 2, 3 (the end is left out). 1..=3 includes the end:

for i in 1..=3 {
    println!("{}", i);
}

This is the loop you'll use most.

  • Use for to print the numbers 1 to 5, one per line.

  • Then use a second for over 0..3 to print Hip hip hooray! three times.

Put it together: FizzBuzz

A famous interview warm-up! For each number from 1 to 15:

  • divisible by both 3 and 5: print FizzBuzz
  • divisible by 3: print Fizz
  • divisible by 5: print Buzz
  • otherwise: print the number

"Divisible by 3" means i % 3 == 0. Check the FizzBuzz case first. Why? Try it the other way and see.

  • Write a for loop over 1..=15.

  • Inside it, use if, else if and else with % to print the FizzBuzz answers.

More in Rust Control Flow & Ownership

Previous: Functions · Next: Ownership