
Control flow lets you run code conditionally or repeatedly. Three main constructs: if, else, and loops.
if/else
Conditions don’t need parentheses, but they must evaluate to a boolean.
fn main() {
let x = 5;
if x > 3 {
println!("x is greater than 3"); // ✅ Prints this
}
}Adding else:
fn main() {
let x = 5;
if x > 10 {
println!("x is greater than 10");
} else {
println!("x is 10 or less"); // ✅ Prints this
}
}else if
Chain conditions:
fn main() {
let x = 6;
if x % 2 == 0 {
println!("x is even");
} else if x % 3 == 0 {
println!("x is divisible by 3");
} else {
println!("x is neither even nor divisible by 3");
}
}if as an Expression
Here’s the weird one: if is an expression, not just a statement. You can assign its result to a variable.
fn main() {
let condition = true;
let x = if condition { 5 } else { 6 };
println!("x: {}", x); // ✅ x: 5
}The values being returned from both branches must be the same type.
let x = if condition { 5 } else { "six" }; // ❌ Error: type mismatchLoops
Rust has three ways to loop: loop, while, and for.
loop
The simplest: run forever until you explicitly break.
fn main() {
let mut count = 0;
loop {
count += 1;
println!("Count: {}", count);
if count == 3 {
break; // ✅ Exit the loop
}
}
}Output:
Count: 1
Count: 2
Count: 3while
Keep looping while a condition is true.
fn main() {
let mut x = 5;
while x > 0 {
println!("x: {}", x);
x -= 1;
}
println!("Blastoff!");
}Output:
x: 5
x: 4
x: 3
x: 2
x: 1
Blastoff!for
Iterate over a collection or range. This is the idiomatic Rust way.
fn main() {
let arr = [10, 20, 30, 40, 50];
for element in arr {
println!("Element: {}", element);
}
}Output:
Element: 10
Element: 20
Element: 30
Element: 40
Element: 50Ranges work too:
fn main() {
for i in 1..4 {
println!("i: {}", i); // ✅ 1, 2, 3 (4 is excluded)
}
}Use ..= to include the end value:
fn main() {
for i in 1..=4 {
println!("i: {}", i); // ✅ 1, 2, 3, 4 (4 is included)
}
}Looping with break and continue
break exits the loop immediately. continue skips to the next iteration.
fn main() {
for i in 1..10 {
if i == 3 {
continue; // Skip 3
}
if i == 7 {
break; // Stop at 7
}
println!("i: {}", i);
}
}Output:
i: 1
i: 2
i: 4
i: 5
i: 6Key takeaway for Future Me:
Use for loops when iterating over collections or ranges. It's safer (no index out of bounds) and more idiomatic than while loops with manual indexing.
And don’t forget: in Rust, if is an expression, so you can assign its result.
