Rust Control Flow: Conditionals and Loops
Use if/else as expressions, loop with loop, while, and for, and see how Rust control flow produces values.
Third post in the basic Rust series. In Rust, control flow is not just about choosing paths — many constructs are expressions that produce values.
If and else#
let score = 85;
if score >= 90 {
println!("Grade: A");
} else if score >= 70 {
println!("Grade: B");
} else {
println!("Grade: C");
}rustThe condition must be a bool — Rust does not coerce numbers to booleans.
If is an expression#
Every branch can return a value. The branches must have the same type:
let grade = if score >= 90 { "A" } else { "B" };
println!("{grade}");rustThis is often cleaner than a separate assignment.
Loop#
loop repeats forever until you break:
let mut counter = 0;
let result = loop {
counter += 1;
if counter == 10 {
break counter * 2; // value after break becomes the result
}
};
println!("{result}"); // 20rustWhile#
let mut n = 3;
while n > 0 {
println!("{n}");
n -= 1;
}rustFor over ranges#
for over a range is the idiomatic way to iterate:
for i in 0..5 {
println!("{i}");
}rust0..5 is exclusive at the end; 0..=5 is inclusive. You can also iterate over collections:
let names = ["Ada", "Grace", "Linus"];
for name in names {
println!("{name}");
}rustBreak and continue#
breakexits the loop immediately.continueskips the rest of the current iteration.
for i in 0..10 {
if i % 2 == 0 {
continue;
}
if i > 7 {
break;
}
println!("{i}");
}
// prints: 1 3 5 7rustConclusion#
Rust’s control flow is expressive and safe: no truthy/falsy surprises, and branches can produce values. Next in this series: functions.