If and Loops in Rust
Conditionals and the three loop forms Rust offers, including using loop as an expression that returns a value.
2 min read
Control flow in Rust will look familiar if you've used C-family languages, with a few distinctly Rust twists — no parentheses required around conditions, and if can produce a value.
if and else
fn main() {
let number = 7;
if number % 2 == 0 {
println!("even");
} else {
println!("odd");
}
}Note there are no parentheses around number % 2 == 0 — Rust doesn't need them, and the curly braces are always required, even for a single statement. That second rule eliminates an entire class of bugs where an unbraced if accidentally only guards the first line.
The condition must be a bool — Rust won't implicitly convert an integer or a string to true/false the way some languages do:
let x = 5;
if x { } // error: expected `bool`, found integerif as an expression
Because if/else is an expression, not just a statement, it can produce a value directly:
fn main() {
let condition = true;
let number = if condition { 5 } else { 6 };
println!("{number}");
}Both branches must produce the same type, and note there's no semicolon after 5 or 6 — a trailing expression without a semicolon is what gets returned.
Three loop forms
loop repeats forever until you explicitly break:
fn main() {
let mut count = 0;
loop {
count += 1;
if count == 5 {
break;
}
}
}loop can also produce a value — pass it to break:
let mut counter = 0;
let result = loop {
counter += 1;
if counter == 10 {
break counter * 2;
}
};
println!("{result}"); // 20while repeats as long as a condition holds:
fn main() {
let mut number = 3;
while number != 0 {
println!("{number}");
number -= 1;
}
println!("liftoff!");
}for iterates over a collection or range, and is by far the most common loop in idiomatic Rust:
fn main() {
let scores = [90, 85, 77];
for score in scores {
println!("{score}");
}
for n in 1..4 { // 1, 2, 3 — exclusive upper bound
println!("{n}");
}
for n in 1..=4 { // 1, 2, 3, 4 — inclusive
println!("{n}");
}
}for avoids the off-by-one errors that come from manually indexing and incrementing with while, and it's what you should default to whenever you're iterating over a known collection or range — reach for while or loop only when the number of iterations genuinely isn't known ahead of time.
Test what you just learned
4 quick questions. Get all of them right to unlock the next lesson.
You can take the quiz without an account — logging in just lets your result count toward your progress.