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
ageis18or more, printYou can vote. Otherwise, printNot 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
kindthat is"even"ifn % 2 == 0, else"odd".Print
7 is oddusingnandkind.
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
loopthat adds 1 tocount, prints it, and stops withbreakoncecountis3.
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
whileto count down: printn, then take 1 away, whilenis 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
forto print the numbers1to5, one per line.Then use a second
forover0..3to printHip 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
forloop over1..=15.Inside it, use
if,else ifandelsewith%to print the FizzBuzz answers.