Control Flow: Decisions and Logic

Control Flow: Decisions and Logic in Rust: At a railway junction the tracks split, and a set of points decides which way a train goes.

The Analogy: The Signal Box

At a railway junction the tracks split, and a set of points decides which way a train goes. The points are not advice. They are a physical object with exactly two positions, and whichever way they are set is where the train ends up. There is no third option and no "probably left". A train that arrives at points nobody has set does not choose for itself; the signal protecting that junction stays at danger and the train stops.

Behind the junction sits the signal box, and inside it the interlocking: a mechanism that refuses to let the signaller set a route that does not add up. You cannot clear a signal onto a line that has no exit. You cannot set two conflicting routes at once. The interlocking is not there because signallers are careless. It is there because a junction with an unaccounted-for route is a junction that will eventually put a train somewhere nobody planned.

Rust's if is the points, and match is the interlocking. if takes a bool -- not a number, not a pointer, not "something non-empty" -- and sends control down exactly one of two tracks. If you use it as an expression, both tracks have to arrive at the same platform, which is why if c { 1 } else { "one" } is a type error rather than a surprise at run time. match goes further: it enumerates the routes, and the compiler checks that every possible value of the subject has one. Leave a case out and you get error[E0004]: non-exhaustive patterns, before the program has ever run.

The consequence is that control flow in Rust is mostly about producing an answer, not about jumping around. if, match, and blocks are all expressions, so the natural shape is let decision = match status { ... }; -- one binding, one place the value comes from, and a compiler guarantee that no path forgot to set it. Once the exhaustiveness check is working for you rather than against you, adding a variant to an enum becomes a build error at every place that needs updating, which is the single most useful refactoring tool the language has.


Syntax or Core Structure

Every branching form in one program. Read the comments -- each one marks a rule that differs from C, Java, or Python.

fn main() {
    let n = 7;

    // The condition must be a `bool`. There is no truthiness, and the
    // parentheses that C requires are not wanted here.
    if n % 2 == 0 {
        println!("{n} is even");
    } else if n % 3 == 0 {
        println!("{n} is divisible by three");
    } else {
        println!("{n} is neither");
    }

    // `if` is an expression, so both arms must produce the same type.
    let size = if n < 10 { "small" } else { "large" };
    println!("size = {size}");

    // `match` tries patterns top to bottom and must cover every value.
    let hint = match n {
        0 => "zero",
        1 | 2 | 3 => "tiny",
        4..=9 => "single digit",
        _ => "big",
    };
    println!("hint = {hint}");

    // `@` binds the matched value; a guard adds a condition to one arm.
    let http = 404;
    let text = match http {
        code @ 200..=299 => format!("ok ({code})"),
        301 | 302 => "redirect".to_string(),
        code if code >= 500 => format!("server error ({code})"),
        code => format!("client error ({code})"),
    };
    println!("text = {text}");

    // `if let` runs a block only when one pattern matches.
    let maybe: Option<i32> = Some(3);
    if let Some(v) = maybe {
        println!("got {v}");
    }
}

Output:

7 is neither
size = small
hint = single digit
text = client error (404)
got 3

Two of those rules are worth seeing fail. First, the condition really must be a bool -- an integer is not "true when non-zero":

fn main() {
    let n = 7;
    if n {
        println!("truthy?");
    }
}

Output (compile error, trimmed):

error[E0308]: mismatched types
 --> src/main.rs:3:8
  |
3 |     if n {
  |        ^ expected `bool`, found `i32`

Second, a match that leaves a value unaccounted for is rejected outright. Here bool has exactly two values and only one has an arm:

fn main() {
    let flag = true;
    let s = match flag {
        true => "yes",
    };
    println!("{s}");
}

Output (compile error, trimmed):

error[E0004]: non-exhaustive patterns: `false` not covered
 --> src/main.rs:3:19
  |
3 |     let s = match flag {
  |                   ^^^^ pattern `false` not covered
  |
help: ensure the match is exhaustive by adding a match arm with a pattern

That second error is the whole point of match. The compiler is not asking you to be tidy; it is refusing to let a value fall through a junction with no route set.


Technical Depth: Patterns, Guards, and Exhaustiveness

How Rust's if differs from the one you already know

DetailRust's ruleWhy it matters
Condition typeMust be exactly boolif ptr, if count, and if list are all compile errors, so "I meant != 0" bugs cannot happen
ParenthesesNot required; rustc's unused_parens lint warns if you add themif (a) && (b) is legal but linted -- the idiom is bare
BracesAlways required, even for one statementThe dangling-else and "added a second line to the body" bug classes do not exist
Assignment in a conditionif x = 5 produces expected bool, found ()The classic = for == typo is a compile error, not a silent truth
ValueIt is an expression; the arms must agree on typelet x = if c { 1 } else { 2 }; replaces the uninitialised-then-assigned dance
Missing elseThen the if must evaluate to ()let x = if c { 1 }; is an error -- there is no implicit default

The patterns you can write in an arm

PatternMatches
404that exact literal
'a'..='z'an inclusive range of char
0..10an exclusive range, stable in patterns since Rust 1.80
200..=299an inclusive numeric range
code @ 500..=599the range, and binds the value to code
_anything, binding nothing
otheranything, binding it to other
Some(v)the Some variant, binding its payload to v
an or-patternany of several patterns, joined by the vertical-bar operator
(a, b)a tuple, destructured into two bindings

Two things about ranges catch people out. ..= is inclusive and .. is exclusive, exactly as in the range expressions from the loops lesson -- so 0..10 covers nine and stops. And ranges in patterns only work on integers, char, and floats; you cannot range-match a &str.

Guards do not count towards exhaustiveness

This is the single most surprising rule in the whole feature, and it is deliberate:

fn sign(n: i32) -> &'static str {
    match n {
        x if x > 0 => "positive",
        x if x <= 0 => "non-positive",
    }
}

A human can see those two arms cover every i32. The compiler cannot, because a guard is arbitrary code that it does not evaluate, so it reports error[E0004]: non-exhaustive patterns: i32::MIN..=i32::MAX not covered. The fix is to make the last arm a pattern with no guard -- _ => "non-positive" -- which is also more honest, since it says "everything else" instead of restating a condition the reader has to check against the first one.

Order matters, and rustc tells you when it stops mattering

Arms are tried top to bottom, so a broad pattern above a narrow one swallows it. Rust catches that with the unreachable_pattern warning:

warning: unreachable pattern
 --> src/main.rs:5:9
  |
5 |         404 => "not found",
  |         ^^^ no value can reach this

That warning fires whenever a _ (or any catch-all binding) sits above a specific arm. Treat it as an error in review: it always means an arm you wrote is dead.

The three shorthand forms

Full match is not always what you want. Rust has three narrower tools:

FormShapeUse it when
if letif let Some(v) = opt { ... } else { ... }Exactly one pattern is interesting and the rest do nothing
let ... elselet Some(v) = opt else { return; };Bind or bail -- the else block must diverge
matches!matches!(v, 'a'..='z')You only want a bool answer, not a branch

let ... else (stable since Rust 1.65) is the one that changes how code looks. Its else block is required to diverge -- return, break, continue, or panic! -- which means the binding it introduces is available for the rest of the function at the outer indentation level, instead of nesting one level deeper for every check. A function with four preconditions stays flat.

Rust 1.88 on the 2024 edition added let chains, so if let Some(a) = x && let Some(b) = y && b > a { ... } is a single condition rather than three nested blocks. If you are on an older toolchain or an older edition, the equivalent is a match on the tuple (x, y).

Here are all three, plus guards, in one runnable program:

fn tier(score: i32) -> &'static str {
    match score {
        s if s < 0 => "invalid",
        0 => "unranked",
        1..=49 => "bronze",
        50..=79 => "silver",
        _ => "gold",
    }
}

fn parse_flag(raw: &str) -> bool {
    matches!(raw.trim().to_ascii_lowercase().as_str(), "1" | "true" | "yes" | "on")
}

fn first_word(line: &str) -> &str {
    let Some(word) = line.split_whitespace().next() else {
        return "<empty>";
    };
    word
}

fn main() {
    for s in [-5, 0, 30, 65, 100] {
        println!("{s:>4} -> {}", tier(s));
    }
    println!("{}", parse_flag(" YES "));
    println!("{}", parse_flag("nope"));
    println!("{:?}", first_word("  hello world  "));
    println!("{:?}", first_word("   "));
}

Output:

  -5 -> invalid
   0 -> unranked
  30 -> bronze
  65 -> silver
 100 -> gold
true
false
"hello"
"<empty>"

Note the shape of tier: the guard is first because it is the only arm that needs one, and the catch-all is last so the match is exhaustive without restating a condition. first_word is the let ... else payoff -- the happy path is the last line of the function, not the inside of a block.


Real World Example: A Retry Policy for HTTP Responses

Deciding whether to retry a failed request is the classic branching problem. The subject is a status code, the rules are ranges with a few exceptions, and getting it wrong means either hammering a server that told you to stop or giving up on a blip. Here it is as one match returning an enum:

#[derive(Debug, PartialEq)]
enum Action {
    Done,
    RetryAfter(u32),
    Fail(&'static str),
}

const MAX_ATTEMPTS: u32 = 3;
const DEFAULT_BACKOFF: u32 = 2;

fn decide(status: u16, retry_after: Option<u32>, attempt: u32) -> Action {
    // A precondition that has nothing to do with the status: return early.
    if attempt >= MAX_ATTEMPTS {
        return Action::Fail("attempts exhausted");
    }

    let backoff = retry_after.unwrap_or(DEFAULT_BACKOFF * attempt.max(1));

    match status {
        200..=299 => Action::Done,
        304 => Action::Done,
        401 | 403 => Action::Fail("not authorised"),
        404 => Action::Fail("not found"),
        408 | 425 | 429 => Action::RetryAfter(backoff),
        501 => Action::Fail("not implemented"),
        500..=599 => Action::RetryAfter(backoff),
        code if code < 100 => Action::Fail("not an http status"),
        _ => Action::Fail("unhandled status"),
    }
}

fn main() {
    let cases = [
        (200u16, None, 0u32),
        (304, None, 0),
        (429, Some(30), 0),
        (429, None, 2),
        (500, None, 1),
        (501, None, 0),
        (403, None, 0),
        (418, None, 0),
        (503, None, 3),
    ];

    for (status, retry_after, attempt) in cases {
        let action = decide(status, retry_after, attempt);
        println!("{status:>4} attempt {attempt} -> {action:?}");
    }
}

Output:

 200 attempt 0 -> Done
 304 attempt 0 -> Done
 429 attempt 0 -> RetryAfter(30)
 429 attempt 2 -> RetryAfter(4)
 500 attempt 1 -> RetryAfter(2)
 501 attempt 0 -> Fail("not implemented")
 403 attempt 0 -> Fail("not authorised")
 418 attempt 0 -> Fail("unhandled status")
 503 attempt 3 -> Fail("attempts exhausted")

The reason this is a match and not a chain of if status == ... is that the subject is a single value and the arms are statements about its shape. Written as an if-chain, the reader has to check every condition against every other one to be sure there is no gap and no overlap. Written as a match, the order encodes precedence explicitly -- 501 sits above 500..=599 because it is the exception to it -- and the compiler guarantees there is no gap. Adding a rule is one line in the right position, not a re-read of the whole function.

The early return at the top earns its place because it is about the attempt counter, not the status. Folding it into the match would mean repeating if attempt >= MAX_ATTEMPTS inside every retryable arm, which is exactly the duplication guards tempt you into. The rule of thumb: preconditions that are independent of the subject belong in guard clauses above the match; conditions that refine one particular case belong in a guard on that arm.

Returning an Action rather than, say, a bool plus an Option<u32> is the part that pays off later. With three variants, every caller has to match on the result, and the exhaustiveness check means that the day someone adds Action::RedirectTo(String), the build breaks at each call site that needs to think about it. A bool plus a number cannot do that; it silently accepts a fourth meaning that nobody handles. Enums and match are one feature, and Module 3 is where that pairing gets its own lesson.

#[derive(Debug, PartialEq)] is not decoration either. Debug is what makes the output above possible with {action:?}, and PartialEq means a test can say assert_eq!(decide(429, None, 2), Action::RetryAfter(4)); -- a single expression that pins one rule of the policy. A retry policy is precisely the kind of logic that is cheap to test and expensive to get wrong, and both of those derives cost one line.


Common Mistakes

  1. Expecting truthiness. if count { ... } where count is an integer gives error[E0308]: expected bool, found i32`. Write the comparison you mean: if count > 0. The same goes for collections -- if !list.is_empty(), never if list`.
  1. Arms that disagree on type. let x = if c { 1 } else { "one" }; fails with error[E0308]: if and else have incompatible types. The error points at the else arm, but the fault is usually that the two branches were written at different times with different intentions.
  1. An if used as an expression with no else. let x = if c { 1 }; is an error: the missing branch would have to produce (). Rust has no implicit zero-value fallback, so supply the else.
  1. Putting _ or a bare binding above a specific arm. Everything below it becomes dead code. rustc says warning: unreachable pattern, and because it is a warning rather than an error it is easy to scroll past in a noisy build.
  1. Assuming guards make a match exhaustive. Two guards that a human can see cover every case still produce error[E0004]. The last arm must be a pattern the compiler can reason about on its own.
  1. Confusing .. and ..= in a pattern. 0..10 stops at nine. Off-by-one in a range arm is silent -- nothing fails to compile, one input just takes the wrong route.
  1. Reaching for match when one case matters. A five-line match with a _ => {} arm is an if let written the long way. Conversely, three nested if lets that all bail out the same way are a match on a tuple, or a let chain.
  1. Moving the subject by accident. match text { s => s.len() } on a String binds by value and moves it, so text is unusable afterwards. Match on a borrow instead -- match &text or match text.as_str() -- which is also what lets you compare against &str literals.
  1. Adding _ to your own enums by reflex. On a type you control, listing every variant is what makes the compiler tell you where to go when you add one. A _ arm silently absorbs the new variant and turns a build error into a run-time surprise. (Upstream types marked #[non_exhaustive] are the exception: there a _ arm is mandatory.)

Best Practices

  • Branch on a value with match and on a condition with if. If you find yourself writing if x == A { } else if x == B { }, the subject is a value and match will check your coverage for you.
  • Order arms from most specific to most general, with the catch-all last. Treat any unreachable_pattern warning as a build failure -- it always means an arm you wrote can never run.
  • Handle subject-independent preconditions with early return above the match, and case-specific refinements with a guard on the arm. Never repeat the same guard on several arms.
  • Let the branch produce the value: let x = match ... ; rather than declaring x first and assigning inside each arm. One binding means one place to look for where x came from.
  • Use let ... else for bind-or-bail so the happy path stays at the outer indentation level, and reserve if let for the cases where the non-matching branch actually does something.
  • Use matches! when the answer is a bool. matches!(c, 'a'..='z' | 'A'..='Z') says what it means; a match returning true and false buries it.
  • Return an enum, not a bool plus loose data, whenever there are more than two outcomes. The exhaustiveness check only helps at call sites if the type has something to be exhaustive about.
  • Avoid _ on enums you own, and prefer if let chains or a tuple match over nesting more than two levels deep. Deep branching in Rust is almost always a sign that the data wants a different shape.

Practice Exercises

  1. Fizz, buzz, and the exhaustiveness trap. Write fn label(n: u32) -> String that returns "fizzbuzz" for multiples of 15, "fizz" for multiples of 3, "buzz" for multiples of 5, and the number itself otherwise -- using a single match on the tuple (n % 3, n % 5). Then try writing it with guards only, and confirm you get error[E0004] until the final arm is guard-free. Print the labels for 1 through 20.
  1. A grade band with a binding. Write fn band(score: i32) -> String that returns "invalid: -4" for negatives, "F" for 0-59, and otherwise "B (73)" style output using code @ 60..=69, code @ 70..=79, and so on up to 100. Anything above 100 should return "invalid: 104". Use exactly one match, and check that you never wrote the same range twice.
  1. Flatten a nest with let ... else. Given fn config_port(raw: Option<&str>) -> u16, return 8080 when the input is None, when the string does not parse as a u16, or when the parsed value is 0. Write it first with nested if let / match, then rewrite it with two let ... else statements and compare the indentation depth of the success path.
  1. Extend the retry policy. Add a RetryAfter cap of 60 seconds and a new Action::Redirect(u16) variant for 301, 302, 307, and 308, then run cargo build and fix every error the exhaustiveness check reports in main. Add three assert_eq! tests that pin the new behaviour, including one proving that a Retry-After header of 900 is clamped.