Module 4 · Control flow & pattern matching
4.1Loops & conditional expressions
Why Rust has no ternary operator, how loop, while and for work, and which loop to reach for where you'd write a C-style for loop.
On this page
- Concept map
- if is an expression
- loop, while and break with a value
- for loops over ranges and collections
- Index and item together
- Borrow, change or consume: &v, &mut v and v
- Labeled loops
- Which one should I use?
- Under the hood
- for is loop plus an iterator
- Why a value needs an else
- Common pitfalls
- Try it yourself
Concept map
| Concept | TypeScript | C# | Rust |
|---|---|---|---|
| Pick a value by condition | cond ? a : b | cond ? a : b | if cond { a } else { b }: if is an expression |
| Loop forever, stop from inside | while (true) and break | while (true) and break | loop, and break value can return a result |
| Count from 0 to 9 | for (let i = 0; i < 10; i++) | for (var i = 0; i < 10; i++) | for i in 0..10 |
| Visit every item | for (const x of xs) | foreach (var x in xs) | for x in &xs (borrow) or for x in xs (move) |
| Index and item together | xs.entries() | xs.Index() (.NET 9+) | xs.iter().enumerate() |
| Leave a nested loop | Labeled statement: outer: and break outer | goto or a flag variable | Loop label: 'outer: and break 'outer |
The if, while and for keywords all exist in Rust, but they work a little differently. if produces a value, so there’s no ?: operator. loop replaces while (true) and can hand back a result. And for has only one form: it walks an iterator, so the C-style for (let i = 0; ...; i++)for (var i = 0; ...; i++) is gone. Ranges and .enumerate() take its place.
if is an expression
In TypeScriptC#, if is a statement: it runs code but has no value. To pick a value you switch to the ternary operator. In Rust, if itself has a value, so one syntax does both jobs.
const score = 72;
const label = score >= 50 ? "pass" : "fail";
console.log(`${score}: ${label}`);var score = 72;
var label = score >= 50 ? "pass" : "fail";
Console.WriteLine($"{score}: {label}");let score = 72;
let label = if score >= 50 { "pass" } else { "fail" };
println!("{score}: {label}");Output
72: pass
Each branch is a block, and a block’s value is its last expression (with no semicolon). Three rules follow from that:
- Braces are required, parentheses aren’t. Write
if score >= 50 { ... }, notif (score >= 50) .... Parentheses around the condition still compile, but the compiler warns that they are unnecessary. - Both branches must have the same type.
if ok { 1 } else { "no" }doesn’t compile. - A value needs an
else. Without one, the missing branch would have no value. The compiler stops you (see Under the hood).
else if chains work as in TypeScriptC#, and the whole chain is still one expression:
let temperature = 31;
let advice = if temperature > 30 {
"stay inside"
} else if temperature > 15 {
"go for a walk"
} else {
"bring a coat"
};
println!("{advice}");Mental model shiftNo ternary, on purpose
Rust doesn’t need ?: because if ... else already is one. The same idea runs through the language: blocks, match and loop are expressions too. When you’d reach for a temporary variable and assign it in each branch, write let x = if ... else ...; instead.
loop, while and break with a value
loop runs forever until a break. It replaces while (true), and it can do one thing while can’t: break can carry a value out, which becomes the value of the whole loop.
let n = 1;
let firstSquare = 0;
while (true) {
if (n * n > 50) {
firstSquare = n * n;
break;
}
n++;
}
console.log(`first square over 50: ${firstSquare}`);var n = 1;
var firstSquare = 0;
while (true)
{
if (n * n > 50)
{
firstSquare = n * n;
break;
}
n++;
}
Console.WriteLine($"first square over 50: {firstSquare}");let mut n = 1;
let first_square = loop {
if n * n > 50 {
break n * n; // the loop's value
}
n += 1;
};
println!("first square over 50: {first_square}");Output
first square over 50: 64
The TypeScriptC# version declares firstSquare before the loop as a mutable variable and assign it from inside. In Rust, first_square is assigned exactly once, from the loop, and never changes. Also note n += 1: Rust has no ++ or -- operators.
while works the way you expect. Use it when the condition is known before each pass:
let mut fuel = 3;
while fuel > 0 {
println!("burning, {fuel} left");
fuel -= 1;
}
println!("empty");A while loop can’t break with a value: it might end because the condition turned false, and then there’d be no value to return. Only loop can.
for loops over ranges and collections
Rust’s for has a single form: for item in something. The something is anything that can produce an iterator. For counting, that’s a range:
for (let i = 0; i < 3; i++) {
console.log(`up ${i}`);
}
for (let i = 3; i >= 1; i--) {
console.log(`down ${i}`);
}for (var i = 0; i < 3; i++)
{
Console.WriteLine($"up {i}");
}
for (var i = 3; i >= 1; i--)
{
Console.WriteLine($"down {i}");
}for i in 0..3 {
println!("up {i}");
}
for i in (1..=3).rev() {
println!("down {i}");
}Output
up 0 up 1 up 2 down 3 down 2 down 1
0..3is half-open: 0, 1, 2. The end is excluded, likei < 3.1..=3is inclusive: 1, 2, 3, likei <= 3..rev()walks a range backwards. There’s no3..1countdown: that range is simply empty.
Index and item together
You rarely need a counter to read a collection. Loop over the collection itself, and add .enumerate() when you also want the position:
const names = ["Ada", "Grace", "Linus"];
for (const [i, name] of names.entries()) {
console.log(`${i + 1}. ${name}`);
}var names = new List<string> { "Ada", "Grace", "Linus" };
foreach (var (i, name) in names.Index())
{
Console.WriteLine($"{i + 1}. {name}");
}let names = ["Ada", "Grace", "Linus"];
for (i, name) in names.iter().enumerate() {
println!("{}. {name}", i + 1);
}Output
1. Ada 2. Grace 3. Linus
.iter() borrows each item in turn, and .enumerate() pairs it with a counter that starts at 0. The (i, name) on the left takes each pair apart, just like [i, name] in TypeScript.var (i, name) in the C# foreach.
Borrow, change or consume: &v, &mut v and v
What you put after in decides what each item is, and what happens to the collection:
const scores = [70, 85, 90];
for (const [i, score] of scores.entries()) {
scores[i] = score + 5;
}
for (const score of scores) {
console.log(score);
}var scores = new List<int> { 70, 85, 90 };
for (var i = 0; i < scores.Count; i++)
{
scores[i] += 5; // a foreach variable can't be assigned
}
foreach (var score in scores)
{
Console.WriteLine(score);
}let mut scores = vec![70, 85, 90];
for score in &mut scores {
*score += 5; // `*` writes through the borrow
}
for score in &scores {
println!("{score}");
}Output
75 90 95
for score in &scoresborrows the vector. Eachscoreis a&i32you can read, andscoresis still yours after the loop.for score in &mut scoresborrows it mutably. Eachscoreis a&mut i32, and*score += 5changes the item in place. No index needed.for score in scoresmoves the vector into the loop. Each item comes out by value, andscoresis gone afterwards. That’s the same move you met in Ownership and move semantics.
Here’s the difference line by line, with one vector looped over twice, first by borrow and then by value:
let team = vec![String::from("Ada"), String::from("Grace")];
for name in &team {
println!("{name}");
}
println!("{} still here", team.len());
for name in team {
println!("{name}");
}
println!("{}", team.len());Rust doesn't compile this: error E0382
error[E0382]: borrow of moved value: `team`
--> main.rs:9:16
|
1 | let team = vec![String::from("Ada"), String::from("Grace")];
| ---- move occurs because `team` has type `Vec<String>`, which does not implement the `Copy` trait
...
6 | for name in team {
| ---- `team` moved due to this implicit call to `.into_iter()`
...
9 | println!("{}", team.len());
| ^^^^ value borrowed here after move
|
note: `into_iter` takes ownership of the receiver `self`, which moves `team`
help: consider iterating over a slice of the `Vec<String>`'s content to avoid moving into the `for` loop
|
6 | for name in &team {
| +| Line | Code | teamowner | &teamshared borrow (&) | loop iteratorowner | teammoved out | What happens |
|---|---|---|---|---|---|---|
| 1 | let team = vec![String::from("Ada"), String::from("Grace")]; | ownsteam starts | ||||
| 2 | for name in &team { | team alive | &&team starts | The loop borrows team. Each name is a &String. | ||
| 3 | println!("{name}"); | team alive | &team alive | |||
| 4 | } | team alive | &team ends | The loop ends, and so does the borrow. | ||
| 5 | println!("{} still here", team.len()); | team alive | OK: team was only borrowed. | |||
| 6 | for name in team { | team ends | ownsloop iterator starts | team moves into the loop. Each name is an owned String. | ||
| 7 | println!("{name}"); | loop iterator alive | movedteam starts | |||
| 8 | } | loop iterator ends | team alive | The loop ends and drops the vector. | ||
| 9 | println!("{}", team.len()); | team ends | errorteam was moved into the loop on line 6 (E0382). |
Nine lines that loop over the vector team twice. The first loop, for name in &team, borrows team on lines 2 to 4, and the borrow ends when the loop ends, so line 5 can still use team. The second loop, for name in team, moves team into the loop on line 6. The loop's iterator owns the vector until the loop ends on line 8, then drops it. From line 7 on, team is moved out, so using it on line 9 is a compile error.
.iter() and .iter_mut() are method spellings of &scores and &mut scores. Use the method when you chain more calls, like .iter().enumerate().
Labeled loops
break and continue act on the innermost loop. To leave an outer loop from inside an inner one, give the outer loop a label:
const grid = [[1, 2], [3, -4], [-5, 6]];
outer: for (const [row, cells] of grid.entries()) {
for (const [col, cell] of cells.entries()) {
if (cell < 0) {
console.log(`first negative at ${row},${col}`);
break outer;
}
}
}int[][] grid = [[1, 2], [3, -4], [-5, 6]];
var found = false; // C# has no labeled break
for (var row = 0; row < grid.Length && !found; row++)
{
for (var col = 0; col < grid[row].Length; col++)
{
if (grid[row][col] < 0)
{
Console.WriteLine($"first negative at {row},{col}");
found = true;
break;
}
}
}let grid = [[1, 2], [3, -4], [-5, 6]];
'outer: for (row, cells) in grid.iter().enumerate() {
for (col, cell) in cells.iter().enumerate() {
if *cell < 0 {
println!("first negative at {row},{col}");
break 'outer;
}
}
}Output
first negative at 1,1
continue 'outer works too, and a labeled loop can break 'outer value.
Common pitfall'outer is a label, not a lifetime
A name that starts with an apostrophe also appears in types, like &'a str or &'static str. Those are lifetimes, covered in Module 11. A loop label looks the same but has nothing to do with them: it sits only in front of loop, while, for (or a plain block), and after break or continue. If you see 'name: right before a loop, it’s a label. Reading Rust’s symbols lists every use of '.
Which one should I use?
| What | When | Why | How |
|---|---|---|---|
if ... else as a value | You’d write cond ? a : b, or assign a variable in each branch. | The variable is set once and needs no mut. Both branches are checked to have the same type. | let label = if ok { "yes" } else { "no" }; |
loop | You stop from inside the body: retries, searches, “until it works”. | Clearer than while true, and break value returns a result. | let x = loop { ... break value; }; |
while | The condition is known before each pass, and you don’t need a result. | Reads like the condition it checks. | while fuel > 0 { ... } |
for over a range | You need numbers: count, repeat, step through a sequence. | No index variable to get wrong, no off-by-one in the condition. | for i in 0..n, for i in 1..=n, for i in (0..n).rev() |
for x in &v | You only read the items. This is the default for collections. | Borrows: no copy, and v is still usable afterwards. | for x in &v or for x in v.iter(). Add .enumerate() for the index. |
for x in &mut v | You change items in place. | No index, and no bounds checks. | for x in &mut v { *x += 1; } |
for x in v | You’re done with v, or each item needs to be owned (moved somewhere else). | Hands you each item by value with no clone. | for x in v. v is moved and can’t be used after the loop. |
Labeled break / continue | You need to leave or skip an outer loop from an inner one. | Replaces flag variables and goto. | 'outer: for ... { break 'outer; } |
Rule of thumb: to visit a collection, write for x in &v and change it to &mut v or v only when you need to. To count, use a range. Use loop when the exit is in the middle, and while when it’s at the top. If you’re typing for i in 0..v.len() just to read v[i], loop over &v instead, with .enumerate() if you need i.
Under the hood
for is loop plus an iterator
A for loop is shorthand. The compiler turns for name in &names { ... } into roughly this:
let names = vec!["Ada", "Grace"];
let mut iter = IntoIterator::into_iter(&names);
loop {
match iter.next() {
Some(name) => println!("{name}"),
None => break,
}
}IntoIterator::into_iterturns the value afterininto an iterator. Each kind of value has its own version:&Vec<T>gives an iterator of&T,&mut Vec<T>gives&mut T, andVec<T>givesTand consumes the vector. That’s the whole difference between&v,&mut vandv.next()returnsSome(item)while there are items, andNoneat the end.SomeandNoneare the two cases ofOption, which if let, while let & let-else introduces.- The loop stops at
None.
A range like 0..10 is itself an iterator: two numbers and a next() that adds one. It allocates nothing. With optimizations on, for i in 0..10 typically compiles to the same machine code as a C-style counting loop, and iterating a vector directly lets the compiler skip the bounds check that v[i] does on every access.
Why a value needs an else
if without else still is an expression, but its value is (), the empty “unit” value. When you try to use that as a string, the compiler rejects it:
let score = 72;
let label = if score >= 50 {
"pass"
};
println!("{label}");Rust doesn't compile this: error E0317
error[E0317]: `if` may be missing an `else` clause
--> main.rs:2:13
|
2 | let label = if score >= 50 {
| _________________^
3 | | "pass"
| | ------ found here
4 | | };
| |_____^ expected `&str`, found `()`
|
= note: `if` expressions without `else` evaluate to `()`
= help: consider adding an `else` block that evaluates to the expected typeTypeScriptC# never runs into this, because its if has no value. In Rust, add the else, or use if as a plain statement and don’t assign it.
Common pitfalls
Common pitfallConditions must be bool
0, "", null and undefined as false. Rust has no truthiness: the condition must be a bool.bool. Code ported from languages with truthiness trips on it.let count = 3;
if count {
println!("not empty");
}Rust doesn't compile this: error E0308
error[E0308]: mismatched types
--> main.rs:2:4
|
2 | if count {
| ^^^^^ expected `bool`, found integerSay what you mean: if count > 0, if !name.is_empty().
Common pitfallThe end of a range is excluded
1..10 stops at 9. Write 1..=10 when the last number counts. And a backwards range like 10..1 is empty, not a countdown: the loop body never runs, and nothing warns you. Write (1..=10).rev().
Common pitfallIndex loops get flagged
Porting for (let i = 0; i < names.length; i++)for (var i = 0; i < names.Count; i++) as for i in 0..names.len() and then reading names[i] compiles, but Clippy (cargo clippy) flags it as a needless range loop. Each names[i] is bounds-checked, and a wrong index panics at runtime. Loop over &names, and use .enumerate() if you also print the position.
Idiomatic RustWrite loop, not while true
while true { ... } compiles, but the compiler warns: “denote infinite loops with loop { ... }”. loop tells the compiler the only way out is a break, so it can tell which variables are definitely assigned after the loop. The compiler doesn’t treat while true that way. And loop is the only loop that can break with a value.
Try it yourself
Exercise: port this to Rust
Port this countdown to Rust. Use a range instead of a counter, and an if expression instead of the ternary.
for (let i = 5; i >= 1; i--) {
const kind = i % 2 === 0 ? "even" : "odd";
console.log(`${i} ${kind}`);
}
console.log("liftoff");for (var i = 5; i >= 1; i--)
{
var kind = i % 2 == 0 ? "even" : "odd";
Console.WriteLine($"{i} {kind}");
}
Console.WriteLine("liftoff");Expected output
5 odd 4 even 3 odd 2 even 1 odd liftoff
Show a hint
Count down with a reversed inclusive range, (1..=5).rev(). Pick the word with an if expression: let kind = if ... { ... } else { ... };
Show a solution
for i in (1..=5).rev() {
let kind = if i % 2 == 0 { "even" } else { "odd" };
println!("{i} {kind}");
}
println!("liftoff");(1..=5).rev() yields 5, 4, 3, 2, 1, so no counter or decrement is needed. The if expression replaces the ternary and gives kind a value once, so it doesn't need mut.
Saved in this browser only.