Skip to content
binshelf/ rust

Search lessons

Type a Rust, TypeScript or C# term, like Option, null or E0382.

    Compare Rust with

    Lessons

    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.

    About 20 minutesBeginner

    On this page
    1. Concept map
    2. if is an expression
    3. loop, while and break with a value
    4. for loops over ranges and collections
    5. Index and item together
    6. Borrow, change or consume: &v, &mut v and v
    7. Labeled loops
    8. Which one should I use?
    9. Under the hood
    10. for is loop plus an iterator
    11. Why a value needs an else
    12. Common pitfalls
    13. Try it yourself

    Concept map

    Concept map: how your language and Rust handle each idea in this lesson
    ConceptTypeScriptC#Rust
    Pick a value by conditioncond ? a : bcond ? a : bif cond { a } else { b }: if is an expression
    Loop forever, stop from insidewhile (true) and breakwhile (true) and breakloop, and break value can return a result
    Count from 0 to 9for (let i = 0; i < 10; i++)for (var i = 0; i < 10; i++)for i in 0..10
    Visit every itemfor (const x of xs)foreach (var x in xs)for x in &xs (borrow) or for x in xs (move)
    Index and item togetherxs.entries()xs.Index() (.NET 9+)xs.iter().enumerate()
    Leave a nested loopLabeled statement: outer: and break outergoto or a flag variableLoop 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.

    TypeScript
    grade.ts
    const score = 72;
    const label = score >= 50 ? "pass" : "fail";
    console.log(`${score}: ${label}`);
    C#
    Grade.cs
    var score = 72;
    var label = score >= 50 ? "pass" : "fail";
    Console.WriteLine($"{score}: {label}");
    Rust
    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 { ... }, not if (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.

    TypeScript
    square.ts
    let n = 1;
    let firstSquare = 0;
    while (true) {
      if (n * n > 50) {
        firstSquare = n * n;
        break;
      }
      n++;
    }
    console.log(`first square over 50: ${firstSquare}`);
    C#
    Square.cs
    var n = 1;
    var firstSquare = 0;
    while (true)
    {
        if (n * n > 50)
        {
            firstSquare = n * n;
            break;
        }
        n++;
    }
    Console.WriteLine($"first square over 50: {firstSquare}");
    Rust
    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:

    TypeScript
    count.ts
    for (let i = 0; i < 3; i++) {
      console.log(`up ${i}`);
    }
    for (let i = 3; i >= 1; i--) {
      console.log(`down ${i}`);
    }
    C#
    Count.cs
    for (var i = 0; i < 3; i++)
    {
        Console.WriteLine($"up {i}");
    }
    for (var i = 3; i >= 1; i--)
    {
        Console.WriteLine($"down {i}");
    }
    Rust
    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..3 is half-open: 0, 1, 2. The end is excluded, like i < 3.
    • 1..=3 is inclusive: 1, 2, 3, like i <= 3.
    • .rev() walks a range backwards. There’s no 3..1 countdown: 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:

    TypeScript
    names.ts
    const names = ["Ada", "Grace", "Linus"];
    for (const [i, name] of names.entries()) {
      console.log(`${i + 1}. ${name}`);
    }
    C#
    Names.cs
    var names = new List<string> { "Ada", "Grace", "Linus" };
    foreach (var (i, name) in names.Index())
    {
        Console.WriteLine($"{i + 1}. {name}");
    }
    Rust
    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:

    TypeScript
    scores.ts
    const scores = [70, 85, 90];
    for (const [i, score] of scores.entries()) {
      scores[i] = score + 5;
    }
    for (const score of scores) {
      console.log(score);
    }
    C#
    Scores.cs
    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);
    }
    Rust
    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 &scores borrows the vector. Each score is a &i32 you can read, and scores is still yours after the loop.
    • for score in &mut scores borrows it mutably. Each score is a &mut i32, and *score += 5 changes the item in place. No index needed.
    • for score in scores moves the vector into the loop. Each item comes out by value, and scores is 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 {
       |             +
    Borrowing loop, then consuming loop
    Borrowing loop, then consuming loop. Each column is a value or a borrow; a mark means it's alive on that line.
    LineCodeteamowner&teamshared borrow (&)loop iteratorownerteammoved outWhat happens
    1let team = vec![String::from("Ada"), String::from("Grace")];ownsteam starts
    2for name in &team {team alive&&team startsThe loop borrows team. Each name is a &String.
    3 println!("{name}");team alive&team alive
    4}team alive&team endsThe loop ends, and so does the borrow.
    5println!("{} still here", team.len());team aliveOK: team was only borrowed.
    6for name in team {team endsownsloop iterator startsteam moves into the loop. Each name is an owned String.
    7 println!("{name}");loop iterator alivemovedteam starts
    8}loop iterator endsteam aliveThe loop ends and drops the vector.
    9println!("{}", team.len());team endserrorteam 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:

    TypeScript
    grid.ts
    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;
        }
      }
    }
    C#
    Grid.cs
    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;
            }
        }
    }
    Rust
    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?

    WhatWhenWhyHow
    if ... else as a valueYou’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" };
    loopYou 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; };
    whileThe 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 rangeYou 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 &vYou 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 vYou change items in place.No index, and no bounds checks.for x in &mut v { *x += 1; }
    for x in vYou’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 / continueYou 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,
        }
    }
    1. IntoIterator::into_iter turns the value after in into an iterator. Each kind of value has its own version: &Vec<T> gives an iterator of &T, &mut Vec<T> gives &mut T, and Vec<T> gives T and consumes the vector. That’s the whole difference between &v, &mut v and v.
    2. next() returns Some(item) while there are items, and None at the end. Some and None are the two cases of Option, which if let, while let & let-else introduces.
    3. 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 type

    TypeScriptC# 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

    TypeScript treats 0, "", null and undefined as false. Rust has no truthiness: the condition must be a bool.
    This is the rule you know from C#: Rust has no truthiness, so the condition must be a 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 integer

    Say 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.

    Starting code in TypeScript
    countdown.ts
    for (let i = 5; i >= 1; i--) {
      const kind = i % 2 === 0 ? "even" : "odd";
      console.log(`${i} ${kind}`);
    }
    console.log("liftoff");
    Starting code in C#
    Countdown.cs
    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.