skip to content

Loops and Conditionals

if is an expression, loop can break with a value, labels exit nested loops, and if let, while let and let-else unpack one pattern. Interviewers check idiomatic control flow.

on this pageshow

questions

6

In Rust, why does `let status = if healthy { 200 } else { "down" };` fail, and how does `if` produce a value?

level: juniorimportance: must knowfreq 70%

answer

  1. expression, not statement
  2. one binding, one type
  3. E0308 names both arms
  4. a missing else is unit

basics

~20 s

In Rust, if is an expression: it evaluates to the value of the block that runs, so every arm must have the same type. An integer arm and a string-slice arm fail with E0308, if and else have incompatible types.

solid answer

~50 s

`if` in Rust is an expression, not a statement: it evaluates to whichever block runs, and a block's value is its final expression written without a semicolon. Because that result goes into one binding with one type, rustc requires the arms to agree. Here the first arm fixes an integer and the `else` arm is a `&str`, so rustc reports E0308, `` `if` and `else` have incompatible types ``, pointing at both arms. The fix is to make them agree: `if healthy { 200 } else { 503 }`, or a small enum when the states really differ. Two related rules come with it: an `if` without `else` evaluates to `()`, so using one as a value is E0317, and the condition must be a `bool`, because Rust has no truthiness for integers or `Option`.

code

rust · 17 lines
rust
fn backoff_ms(attempt: u32, max_ms: u64) -> u64 {
    // Each arm is an expression; both are u64, so the whole `if` is a u64.
    let delay = if attempt == 0 {
        0
    } else if attempt < 10 {
        100u64 << attempt
    } else {
        max_ms
    };
    delay.min(max_ms)
}

fn main() {
    let label = if backoff_ms(3, 5_000) > 500 { "slow" } else { "fast" };
    println!("{} {}", backoff_ms(3, 5_000), label);
    println!("{}", backoff_ms(12, 5_000));
}

go deeper

for a junior

Say that if is an expression, show let x = if c { a } else { b }, and state that both arms must have the same type.

for a middle

Explain where the value comes from: the executed block's final expression. Name E0308 for mismatched arms and E0317 for a missing else.

for a senior

Show how diverging arms with type never fit any arm type, and when a mismatch means the outcomes deserve an enum rather than a forced common type.

for a principal

Frame expression-oriented control flow as a review standard: bind results immutably, model distinct outcomes as types, and let the compiler reject half-initialised values.

## `if` is an expression In Rust almost everything that does work is an **expression**: it produces a value. An `if` is one of them. The Reference states the rule directly: an `if` expression *evaluates to the same value as the executed block, or `()` if no block is evaluated*, and *an `if` expression must have the same type in all situations*. A block's value is its **final operand**, the last expression written without a trailing semicolon. That is why Rust needs no separate conditional (ternary) operator. You write the choice as an ordinary `if`/`else` and bind it: ```rust let label = if latency_ms > 500 { "slow" } else { "fast" }; ``` The two arms are both `&'static str`, so `label` is a `&'static str`. ## One type for every arm The compiler checks the arms against each other because the whole `if` has to have a single type. In `let status = if healthy { 200 } else { "down" };` the first arm makes the type an integer, the second arm is a `&str`, and nothing converts one into the other. rustc 1.99 reports: - **E0308, `` `if` and `else` have incompatible types ``**, with the first arm labelled *expected because of this* and the second labelled *expected integer, found `&str`*. | Form | Type of the whole `if` | |---|---| | `if c { 1 } else { 2 }` | the integer type both arms share (`i32` by default) | | `if c { 1 } else if d { 2 } else { 3 }` | the same: every branch must agree | | `if c { do_work(); }` with no `else` | `()` | | `if c { panic!("bad") } else { 5 }` | the non-diverging arm's type | | `if c { 200 } else { "down" }` | none: E0308 | The arms can still unify through ordinary coercions. When the binding is annotated `&str`, an arm producing `&String` coerces to `&str`, so `let s: &str = if c { &owned } else { "lit" };` compiles. An arm that calls `panic!`, `return` or `continue` has the never type `!`, which coerces to anything, so it never causes a mismatch; the material on diverging expressions covers `!` itself. ## The errors you will meet 1. **E0308, incompatible types**: two arms with different types, as above. Fix the arms, not the binding. 2. **E0317, `` `if` may be missing an `else` clause ``**: `let delay = if retries > 0 { 100 * retries };`. When the condition is false no block runs, the `if` evaluates to `()`, and `()` is not an integer. rustc adds the note *`if` expressions without `else` evaluate to `()`* and suggests an `else` arm of the expected type. 3. **E0308, expected `bool`, found integer**: `if retries { ... }`. The condition must be a `bool`. Write the comparison you mean: `retries > 0`, `opt.is_some()`, `!list.is_empty()`. A trailing semicolon inside an arm is a fourth source of the same E0308: `{ 200; }` is a block whose value is `()`. The rules for blocks, statements and that semicolon belong to the material on blocks and shadowing; here the point is only that each arm's last expression is its value. ## Idiomatic use - **Bind the result instead of mutating a placeholder.** `let delay = if attempt == 0 { 0 } else { base << attempt };` keeps `delay` immutable and initialised exactly once. - **Chain `else if` for ordered tests.** Each condition is checked top to bottom and the first true one wins; the final `else` makes the chain total, so it can produce a value. - **Use the `if` directly as a function's tail.** A function body is a block, so `fn sign(n: i32) -> i32 { if n < 0 { -1 } else { 1 } }` returns whichever arm runs, with no `return` keyword. - **Reach for `match` when the choice is over an enum's variants or many literal cases.** The material on `match` covers exhaustiveness; `if` is for boolean conditions, and `if let` for testing one pattern. ## Why the rule is strict A value-producing `if` is checked at compile time like any other expression: the type of `status` must be known before the program runs, whichever branch is taken. Allowing one arm to be an integer and the other a string would need a runtime type tag that Rust does not add implicitly. When the two outcomes really differ, model them: an `enum Health { Up(u16), Down(&'static str) }` makes both arms the same type on purpose, and later code has to handle both cases.

  • Why does `if retries { ... }` with `retries: u32` not compile in Rust?
    An `if` condition must have type `bool`; Rust never treats a non-zero integer, a `Some` or a non-empty collection as true. rustc reports E0308, expected `bool`, found integer. Write the test you mean: `if retries > 0`, `if opt.is_some()`, `if !list.is_empty()`.
  • What does rustc say about `let delay = if retries > 0 { 100 * retries };`?
    E0317, `` `if` may be missing an `else` clause ``. When the condition is false no block runs and the `if` evaluates to `()`, which cannot be an integer. Add an `else` arm of the same type, such as `else { 0 }`, or restructure so the `if` is only a statement.
  • Can one arm of a value-producing `if` call `panic!` while the other yields a `u32`?
    Yes. `panic!` has the never type `!`, which coerces to any type, so `let v: u32 = if bad { panic!("no input") } else { 5 };` compiles and the `if` takes its type from the non-diverging arm. The same holds for `return`, `break` and `continue` in an arm.

  • if is a statement in Rust, so you need a mutable variable to capture its result
  • rustc converts mismatched arm types, such as an integer and a string slice, automatically
  • an if without else yields zero or a default value when the condition is false
  • an integer or an Option can be used directly as an if condition
  • a semicolon after an arm's last expression does not change the arm's value
open as a page

In Rust, how does `let result = loop { ... break outcome; };` yield a value, and why can't `while` or `for` do the same?

level: juniorimportance: must knowfreq 72%

basics

~20 s

A Rust loop evaluates to the operand of the break that ends it, so break outcome hands outcome to the let. A while or for loop can end without any break, so it always evaluates to (), and a valued break inside it is E0571.

open as a page

In a Rust nested grid search, what do `break 'rows` and `continue 'rows` do, and when would you use a labeled block instead?

level: middleimportance: should knowfreq 45%

basics

~20 s

A label such as 'rows: names an enclosing loop: break 'rows leaves it from any depth and continue 'rows starts its next iteration. Since Rust 1.65 a labeled block, 'check: { ... }, can be left early with break 'check value without being a loop.

open as a page

In a Rust line parser, what does `let Some((key, value)) = line.split_once('=') else { return None; };` do, and why must its `else` diverge?

level: middleimportance: should knowfreq 50%

basics

~20 s

let-else, stable since Rust 1.65, binds key and value for the rest of the block when the pattern matches; otherwise its else block runs. That block must diverge (return, break, continue, panic) because no value exists to bind, and a non-diverging else is E0308.

open as a page

In Rust, how does `while let Some(name) = stack.pop()` drain a work stack, and why may its body push onto `stack`?

level: middleimportance: should knowfreq 58%

basics

~20 s

while let calls stack.pop() before every iteration and runs the body while it returns Some(name), stopping at None. pop returns an owned value and keeps no borrow of stack, so the body may push; a for loop over &stack borrows it for the whole loop.

open as a page

In Rust, what does `if let Some(header) = req.auth && let Some(token) = header.strip_prefix("Bearer ")` allow, and why does it fail on edition 2021?

level: seniorimportance: should knowfreq 35%

basics

~20 s

A let chain joins let patterns and bool tests with && in one if or while condition, each binding visible to later operands. It is stable since Rust 1.88 on the 2024 edition only, so edition 2021 rejects it.

open as a page