Lesson 5
Control Flow
Master if/else, loop, while, for loops, and ranges in Rust.
If / Else
Rust's if/else works like you'd expect, but the condition does not need parentheses. Also, if is an expression -- it can return a value, so you can use it on the right side of a let.
let status = if score > 50 { "pass" } else { "fail" };
Loops
Rust gives you three loop types. loop runs forever until you break. while runs as long as a condition is true. for iterates over a range or collection -- it's the most common and the safest.
Ranges
Use 1..11 for 1 through 10 (exclusive end) or 1..=10 for 1 through 10 (inclusive). Combine these with for and you've got clean, readable iteration.
The code below runs a classic FizzBuzz. Read through it, then hit Run.
Try it
fn main() {
// if/else as an expression
let number = 7;
let parity = if number % 2 == 0 { "even" } else { "odd" };
println!("{} is {}", number, parity);
// for loop with range -- FizzBuzz!
println!("\n--- FizzBuzz (1 to 15) ---");
for n in 1..=15 {
if n % 15 == 0 {
println!("FizzBuzz");
} else if n % 3 == 0 {
println!("Fizz");
} else if n % 5 == 0 {
println!("Buzz");
} else {
println!("{}", n);
}
}
// while loop
println!("\n--- Countdown ---");
let mut count = 5;
while count > 0 {
println!("{}...", count);
count -= 1;
}
println!("Liftoff!");
// loop with break (returns a value!)
let mut counter = 0;
let result = loop {
counter += 1;
if counter == 10 {
break counter * 2;
}
};
println!("\nLoop result: {}", result);
}Challenge
Modify the FizzBuzz to count from 1 to 20 instead of 1 to 15.
Previous: Functions
Next: Ownership