skip to content

Expressions and Scalars

Rust is expression-oriented: blocks, if and loop yield values, integers have fixed widths and checked overflow, and casts are explicit. Interviewers open with these rules.

on this pageshow

explore

questions

17

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 Rust, how does shadowing with `let port: u16 = port.parse()?;` differ from reassigning a `let mut port` binding?

level: juniorimportance: must knowfreq 72%

basics

~20 s

Shadowing declares a brand-new variable that reuses the name, so port can go from &str to u16 and every binding stays immutable. Assigning to a let mut binding overwrites one variable, whose type never changes.

open as a page

In Rust, what happens when a ledger's `u8` pending-transfer counter at 255 is incremented, in a debug build and in a release build?

level: juniorimportance: must knowfreq 80%

basics

~20 s

A debug build panics with "attempt to add with overflow"; a default release build silently wraps the counter to 0. Neither is undefined behaviour, and code that means to wrap or stop must say so explicitly.

open as a page

Why does rustc reject a Rust `fn parse_port(s: &str) -> u16` with E0308 when its last line ends in a semicolon?

level: middleimportance: must knowfreq 66%

basics

~20 s

A block's value is its final expression written without a semicolon. The semicolon turns that line into a statement, so the body has no final operand, evaluates to (), and fails with E0308 against the declared u16.

open as a page

In Rust, how do `checked_add`, `wrapping_add`, `saturating_add` and `overflowing_add` differ when summing untrusted `u64` token amounts in a ledger?

level: middleimportance: must knowfreq 72%

basics

~10 s

checked_add returns None on overflow, wrapping_add wraps modulo 2^64, saturating_add clamps at u64::MAX, and overflowing_add returns the wrapped value plus a bool. For untrusted ledger amounts, use checked_add and reject the batch.

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 is the difference between a `const` item and a `static` item, and when must you choose `static`?

level: middleimportance: should knowfreq 55%

basics

~20 s

A const is a compile-time value copied into every place that uses it, with no fixed address. A static is one allocation for the whole program; choose it when you need a single address, interior mutability or a large table.

open as a page

In Rust, what do `300_i32 as u8`, `-1_i32 as u32` and `200_u8 as i8` evaluate to, and why does `as` never report the loss?

level: middleimportance: should knowfreq 64%

basics

~20 s

They give 44, 4294967295 and -56. An integer as cast truncates to the target's low bits, reinterprets the same bits across signedness, and sign- or zero-extends when widening; it is infallible by definition, so it cannot report anything.

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

Why does a Rust counter declared `const REQUESTS: AtomicU64 = AtomicU64::new(0);` and bumped with `fetch_add` on every request always read zero?

level: seniorimportance: should knowfreq 28%

basics

~20 s

Each mention of a const creates a new temporary copy of its value, so every fetch_add increments a throwaway AtomicU64 and load reads another fresh zero. Declare it static so every call uses one allocation.

open as a page

In Rust, why does a `match` arm that runs `return Err(...)` type-check beside an arm yielding a `u16`, and what is the type `!`?

level: seniorimportance: should knowfreq 34%

basics

~20 s

return, panic!, continue and an endless loop have the never type !, which has no values, so it coerces to whatever type the other arms need. On stable Rust, ! is written only as a return type.

open as a page

A Rust ledger splits signed `i64` adjustments across holders; what do `/` and `%` do with negative amounts, zero holders and `i64::MIN / -1` in a release build?

level: seniorimportance: should knowfreq 36%

basics

~20 s

Integer / rounds toward zero and % takes the dividend's sign, so -1001 split four ways is -250 remainder -1. Dividing by zero and i64::MIN / -1 panic in every build, release included; checked_div and checked_rem return None instead.

open as a page

A Rust device stores a sensor's `f64` reading as `reading as u8`; what does it store for 300.7, -4.2 and NaN, and how should it guard the cast?

level: seniorimportance: should knowfreq 40%

basics

~10 s

It stores 255, 0 and 0: a float-to-integer as cast truncates toward zero, saturates at the target's range and turns NaN into 0. A guard must round, then reject non-finite and out-of-range values explicitly.

open as a page

As the lead of a Rust codebase doing balance and fee arithmetic on untrusted amounts, what arithmetic rule would you set, and how would you enforce it?

level: principalimportance: should knowfreq 30%

basics

~20 s

Make every overflow-prone operation on money state its intent: checked methods returning errors for untrusted amounts, strict methods for internal invariants, Wrapping only where modular math is meant. Enforce it with Clippy's arithmetic_side_effects lint in money modules and amount newtypes.

open as a page