Control flow: if, loops and ranges
A useful program makes decisions and repeats tasks. Rust offers if to decide and three ways to repeat: loop, while and for. They are simple blocks or expressions, but with two Rust-specific rules: conditions must be of type bool (there is no "truthy" number) and they do not need parentheses. In this lesson you will see each one, how to leave a loop and how to label nested loops.
if as an expression
if, else if and else work as you expect, but if is also an expression: you can assign its result to a variable. For that, all branches must return the same type, and each branch ends without a semicolon. This replaces the ternary operator (a ? b : c) found in other languages. If you write if x { ... } with an integer x, the compiler rejects the code: compare explicitly, for example x != 0.
fn main() {
let temperature = 28;
if temperature > 30 {
println!("hot");
} else if temperature > 20 {
println!("warm");
} else {
println!("cold");
}
let label = if temperature % 2 == 0 { "even" } else { "odd" };
println!("{temperature} is {label}");
}loop, while and for
loop repeats forever until you use break; also, break can return a value: let r = loop { ... break 42; }. while repeats as long as a condition is true. for walks over any iterator and is the most used and safest option, because there is no index that can go out of range. Ranges are the easiest way to count: 1..4 goes from 1 to 3 (the end is excluded) and 1..=4 includes 4. With .rev() you go backwards and with .step_by(n) you jump n at a time.
fn main() {
let mut counter = 0;
let result = loop {
counter += 1;
if counter == 5 {
break counter * 10; // loop returns 50
}
};
println!("result = {result}");
let mut n = 3;
while n > 0 {
println!("{n}...");
n -= 1;
}
println!("liftoff!");
for i in 1..=3 {
print!("{i} ");
}
println!();
for i in (0..10).step_by(3).rev() {
print!("{i} ");
}
println!();
let names = ["Ana", "Luis", "Eva"];
for (i, name) in names.iter().enumerate() {
println!("{i}: {name}");
}
}continue, break and labels
continue jumps to the next iteration of the loop and break ends it. When you have a loop inside another, break only affects the innermost one; to leave an outer one you give it a label with a single quote, like 'outer: for ..., and write break 'outer. It is uncommon, but it avoids awkward helper flags. A typical case is searching for a value in a grid and stopping as soon as you find it.
fn main() {
let grid = [[1, 2, 3], [4, 5, 6], [7, 8, 9]];
let target = 6;
'search: for (r, row) in grid.iter().enumerate() {
for (c, value) in row.iter().enumerate() {
if *value % 2 == 1 {
continue; // skip odd numbers
}
if *value == target {
println!("found {target} at row {r}, column {c}");
break 'search;
}
}
}
}A detail about while and loop: the compiler understands that a loop without break never finishes, so it can accept code that "does not return" after it. A while, in contrast, may not run even once, so Rust does not let it return a value with break. If you need to compute something while repeating, accumulate the result in a mut variable declared before the loop, as we do with counter, or use a loop with break value.
One last warning about ranges: 0..n with n equal to zero is an empty range and the loop simply does not run, with no error. And when you walk over a collection, do not use the range 0..len to access by index if you do not need the index; walk over the elements directly with for item in &list or, if you need both, with enumerate as in the previous example.
fn main() {
for n in 1..=20 {
if n % 15 == 0 {
println!("FizzBuzz");
} else if n % 3 == 0 {
println!("Fizz");
} else if n % 5 == 0 {
println!("Buzz");
} else {
println!("{n}");
}
}
}Test what you learned
Question 1 of 5Which range includes 5 as its last value?
✎ My notes
Saved only in this browser. Sign in to keep it in your account.0/5000 characters