Rust Control Flow if else and Loops
Control flow is how you make a program take different paths or repeat actions. Without control flow, programs run from top to bottom in a straight line. With it, you can make decisions and repeat tasks.
The if Expression
An if expression runs a block of code only when a condition is true.
fn main() {
let temperature = 35;
if temperature > 30 {
println!("It is hot outside.");
}
}
Output:
It is hot outside.
The condition temperature > 30 evaluates to true, so the code inside the block runs.
if with else
Add an else block to handle the case when the condition is false:
fn main() {
let temperature = 20;
if temperature > 30 {
println!("It is hot outside.");
} else {
println!("The weather is pleasant.");
}
}
Output:
The weather is pleasant.
if with else if
Chain multiple conditions with else if:
fn main() {
let score = 75;
if score >= 90 {
println!("Grade: A");
} else if score >= 75 {
println!("Grade: B");
} else if score >= 60 {
println!("Grade: C");
} else {
println!("Grade: F");
}
}
Output:
Grade: B
The Crossroads Diagram
score = 75
│
├─ score >= 90? → No
│
├─ score >= 75? → Yes → println!("Grade: B")
│ STOP, skip rest
├─ score >= 60? (skipped)
│
└─ else (skipped)
if as an Expression
In Rust, if is an expression. It can return a value and be assigned to a variable:
fn main() {
let is_raining = true;
let message = if is_raining { "Bring an umbrella." } else { "Enjoy the sunshine." };
println!("{}", message);
}
Output:
Bring an umbrella.
Both branches must return the same type. If one returns a string and the other returns a number, the compiler will reject the code.
Loops
A loop repeats a block of code. Rust provides three loop types: loop, while, and for.
1. loop — Repeat Forever Until Told to Stop
The loop keyword creates an infinite loop. Use break to exit:
fn main() {
let mut count = 0;
loop {
count += 1;
if count == 3 {
break;
}
println!("Count: {}", count);
}
println!("Loop ended.");
}
Output:
Count: 1 Count: 2 Loop ended.
Return a Value from loop
Place a value after break to return it from the loop:
fn main() {
let mut counter = 0;
let result = loop {
counter += 1;
if counter == 5 {
break counter * 2;
}
};
println!("Result: {}", result);
}
Output:
Result: 10
2. while — Repeat While a Condition Is True
fn main() {
let mut lives = 3;
while lives > 0 {
println!("Lives remaining: {}", lives);
lives -= 1;
}
println!("Game over.");
}
Output:
Lives remaining: 3 Lives remaining: 2 Lives remaining: 1 Game over.
The Countdown Diagram
lives = 3 │ ├─ lives > 0? Yes → print "Lives: 3" → lives = 2 ├─ lives > 0? Yes → print "Lives: 2" → lives = 1 ├─ lives > 0? Yes → print "Lives: 1" → lives = 0 └─ lives > 0? No → exit loop → "Game over."
3. for — Loop Over a Collection
The for loop visits every element in a collection one at a time. It is the most commonly used loop in Rust because it is safe — it never goes out of bounds:
fn main() {
let fruits = ["apple", "banana", "cherry"];
for fruit in fruits {
println!("I like {}.", fruit);
}
}
Output:
I like apple. I like banana. I like cherry.
Loop Over a Range
A range generates numbers between two values. Use 1..5 for 1, 2, 3, 4 (5 not included) or 1..=5 for 1, 2, 3, 4, 5 (5 included).
fn main() {
for number in 1..=5 {
println!("Number: {}", number);
}
}
Output:
Number: 1 Number: 2 Number: 3 Number: 4 Number: 5
continue — Skip to the Next Iteration
continue skips the rest of the current loop body and moves to the next iteration:
fn main() {
for n in 1..=6 {
if n % 2 == 0 {
continue;
}
println!("{}", n);
}
}
Output:
1 3 5
Loop Labels
When you have a loop inside another loop, use labels to specify which loop break or continue applies to. Labels start with a single quote:
'outer: for x in 0..3 {
for y in 0..3 {
if x == 1 && y == 1 {
break 'outer;
}
println!("x={}, y={}", x, y);
}
}
Choosing the Right Loop
Situation Best Loop --------- --------- Run forever until break loop Repeat while a condition is true while Walk through every item in a list for Walk through a range of numbers for with range
