Skip to content

Control Flow

In Rust, if is an expression — it evaluates to a value. This means you can use it on the right-hand side of a let binding. All branches must produce the same type.

fn main() {
let score = 75;
let grade = if score >= 90 { "A" } else if score >= 75 { "B" } else { "C" };
println!("grade = {}", grade);
}

No parentheses are required around the condition, and curly braces around the body are mandatory.

When you do not need the result, use if as a statement:

fn main() {
let n = 7;
if n % 2 == 0 {
println!("even");
} else {
println!("odd");
}
}

loop runs its body indefinitely until an explicit break. Unlike other languages, Rust’s loop can return a value through break.

fn main() {
let mut counter = 0;
let result = loop {
counter += 1;
if counter == 5 {
break counter * 2; // the loop evaluates to this value
}
};
println!("result = {}", result); // 10
}

while repeats as long as its condition is true. It cannot return a value via break.

fn main() {
let mut n = 1;
while n < 4 {
print!("{} ", n);
n += 1;
}
println!(); // newline
}

for — Iterate Over Collections and Ranges

Section titled “for — Iterate Over Collections and Ranges”

for is the most common loop in Rust. It iterates over any type that implements the Iterator trait — including ranges and arrays.

fn main() {
// Exclusive range: 1, 2, 3
for i in 1..4 {
print!("{} ", i);
}
println!();
// Inclusive range: 1, 2, 3, 4, 5
for i in 1..=5 {
print!("{} ", i);
}
println!();
// Iterating over an array
let fruits = ["apple", "banana", "cherry"];
for fruit in fruits {
print!("{} ", fruit);
}
println!();
}

Prefer for over while with a manual index whenever possible — it is safer and more expressive.

fn main() {
// if as an expression
let score = 75;
let grade = if score >= 90 { "A" } else if score >= 75 { "B" } else { "C" };
println!("grade = {}", grade);
// loop returning a value via break
let mut counter = 0;
let result = loop {
counter += 1;
if counter == 5 {
break counter * 2;
}
};
println!("loop result = {}", result);
// while loop
let mut n = 1;
while n < 4 {
print!("{} ", n);
n += 1;
}
println!();
// for with a range
for i in 1..=3 {
print!("{} ", i);
}
println!();
// for over an array
let nums = [10, 20, 30];
for val in nums {
print!("{} ", val);
}
println!();
}
What is required for Rust's if to be used as an expression on the right side of let?
How does loop return a value in Rust?
What is the difference between 1..4 and 1..=4?
Which loop construct is most idiomatic in Rust when iterating over a collection?