Concise Control with If Let

Concise Control with If Let in Rust: A night porter does not run the daytime sorting procedure for every knock at the door.

The Analogy: The Night Porter's Peephole

A night porter does not run the daytime sorting procedure for every knock at the door. They slide the peephole cover across, look, and if it is the courier with the overnight bag, they open the door and take the bag in. If it is anything else, the cover slides shut and nothing further happens. One question, one action, and no obligation whatsoever to have a plan for every possible visitor.

The cost of that convenience is real, and it is worth naming before you enjoy it. The daytime procedure has a supervisor who checks that every category of caller is accounted for -- couriers, cleaners, contractors, the occasional lost guest. The peephole has no supervisor. If a new kind of delivery starts arriving at three in the morning, the porter will simply not open the door, and nobody will be told that a case was missed. The silence is the whole trade.

Sometimes there is a second question worth asking: if not the courier, then perhaps the cleaner. The porter can look again, and again, and the door still opens for exactly one kind of caller at a time. But by the third or fourth cover-slide it has stopped being a shortcut, and the daytime procedure -- one list, checked once, with the supervisor watching -- would have been both shorter and safer.

And when the deliveries arrive in a queue, the porter keeps opening the door for as long as there is another bag on the step, and stops the moment there is not. That last shape is a loop whose condition and whose unpacking are the same act: keep going while the answer to the one question is "yes, here is another one".


Syntax or Core Structure

if let takes a pattern and a value, and runs its block only if the pattern matches -- binding whatever the pattern names for the duration of that block.

enum Slot {
    Empty,
    Parcel { id: u32, kg: u32 },
    Note(String),
}

fn main() {
    let slots = [
        Slot::Parcel { id: 41, kg: 3 },
        Slot::Note(String::from("ring twice")),
        Slot::Empty,
    ];

    for s in &slots {
        if let Slot::Parcel { id, kg } = s {
            println!("took parcel {id} at {kg} kg");
        }
    }

    println!();

    let stored: Option<u32> = None;
    if let Some(kg) = stored {
        println!("stored weight {kg}");
    } else {
        println!("nothing stored");
    }

    println!();

    for s in &slots {
        if let Slot::Parcel { id, .. } = s {
            println!("parcel {id}");
        } else if let Slot::Note(text) = s {
            println!("note: {text}");
        } else {
            println!("slot empty");
        }
    }

    println!();

    let mut queue = vec![10, 20, 30];
    while let Some(top) = queue.pop() {
        println!("popped {top}, {} left", queue.len());
    }
}

Output:

took parcel 41 at 3 kg

nothing stored

parcel 41
note: ring twice
slot empty

popped 30, 2 left
popped 20, 1 left
popped 10, 0 left

Four shapes in one program. The first loop is the bare if let: one case of interest, and the other two slots pass by without a line of code mentioning them. The second block adds an else, which is what you want when the absence is itself worth reporting. The third is an else if let chain, and it is the shape to be suspicious of -- three questions asked one at a time, doing the job a match would do in one. The fourth is while let, where the loop's condition and its unpacking are a single act.

There is one diagnostic worth knowing, because it catches a genuine slip:

warning: irrefutable `if let` pattern
 --> src/main.rs:4:8
  |
4 |     if let x = value {
  |        ^^^^^^^^^^^^^

(rustc adds a note that the pattern will always match and a help suggesting a plain let; both are trimmed here.) A pattern that cannot fail makes the if meaningless -- the block always runs -- and the usual cause is a variant name typed as a lowercase identifier, which Rust reads as a fresh binding rather than as the variant you meant.


Technical Depth: One Question, and What It Costs

It is sugar, and it is still an expression

if let PAT = EXPR { A } else { B } is exactly match EXPR { PAT => A, _ => B }. Nothing is faster, nothing is slower, and no capability is added -- the only change is the shape on the page. With no else, the elided arm is _ => (), which is why a bodiless if let must evaluate to the unit type.

Because it is an expression, it can produce a value, and then both branches must agree on the type.

fn main() {
    let raw: Option<&str> = Some("9000");

    let port: u16 = if let Some(text) = raw {
        text.parse().unwrap_or(8080)
    } else {
        8080
    };
    println!("port {port}");

    let flag: Option<bool> = Some(true);
    if let Some(true) = flag {
        println!("flag set");
    }

    let label = if let Some(text) = raw { text } else { "unset" };
    println!("label {label}");
}

Output:

port 9000
flag set
label 9000

Three uses, three roles. The first if let is the right-hand side of a let, so both branches have to produce a u16. The second has no else and no value, so its block must evaluate to () -- and its pattern is Some(true), a literal nested inside the variant, which is a reminder that if let accepts every pattern match does. The third is the one-line form that replaces a match when you want a value and a fallback and nothing else.

Note also that all three read raw and raw survives, because Option<&str> is Copy. With an Option<String> the first if let Some(text) = raw would move the string out and the later uses would be error[E0382]. Matching against a reference -- if let Some(text) = &raw -- is the fix you will reach for; raw.as_ref() and an outright clone are the other two.

Choosing a form

FormChecks every caseBindsReach for it when
matchyesyesthere are three or more outcomes, or a new variant must be caught
if letnoyesexactly one shape matters and the rest need nothing
if let with elsenoyesone shape matters and there is a single fallback
else if let chainnoyestwo shapes, and a match would need awkward nesting
while letnoyesdraining a source until it stops producing
let with elsenoyesthe shape is required and the failure path diverges
matches!nonoyou want a plain bool, typically inside a filter

The "checks every case" column is the whole decision. Only match will fail to compile when a variant is added, so only match protects a piece of logic that must be revisited every time the type grows. Everything else in that table is a deliberate opt-out, and the right way to think about it is: if a new variant appeared tomorrow, would silence be the correct behaviour here? For a metrics counter or a cache-warming pass, yes. For pricing, billing, or access control, no.

let with else, and while let that stops

struct Job {
    id: u32,
    owner: Option<String>,
}

fn assign(j: &Job) -> String {
    let Some(owner) = &j.owner else {
        return format!("job {} unassigned", j.id);
    };
    format!("job {} owned by {owner}", j.id)
}

fn main() {
    let jobs = [
        Job { id: 1, owner: Some(String::from("ada")) },
        Job { id: 2, owner: None },
    ];
    for j in &jobs {
        println!("{}", assign(j));
    }

    let mut items = vec![Some(1), Some(2), None, Some(4)];
    items.reverse();

    let mut sum = 0;
    while let Some(Some(n)) = items.pop() {
        sum += n;
    }
    println!("sum {sum}, {} left", items.len());
}

Output:

job 1 owned by ada
job 2 unassigned
sum 3, 1 left

let ... else is the shape for a precondition. Its pattern is refutable, which a plain let forbids, and the price is that the else block must diverge -- return, break, continue, or a panic. In exchange, the binding lives in the enclosing scope rather than inside a block, so the rest of the function stays at one level of indentation instead of drifting right with every check.

The while let result is the one to remember. items after reverse is [Some(4), None, Some(2), Some(1)], so pop yields Some(Some(1)) and Some(Some(2)), giving sum = 3. The next pop returns Some(None), which does not match Some(Some(n)), so the loop ends -- it does not skip that entry and continue. And the entry is gone regardless, because pop already removed it before the pattern was tested. One element remains. A loop that should skip rather than stop needs for plus an inner if let, or .flatten().

matches! when you only want a bool

fn main() {
    let values = [Some(3), Some(12), None];

    let mut small = 0;
    for v in values {
        if matches!(v, Some(n) if n < 10) {
            small += 1;
        }
    }
    println!("small {small}");

    println!("lowercase: {}", matches!('x', 'a'..='z'));
    println!("digit: {}", matches!('X', '0'..='9'));
}

Output:

small 1
lowercase: true
digit: false

matches! expands to a match returning true for your pattern and false for everything else, and it accepts a guard. It is the honest choice whenever the answer you want is a boolean rather than a branch -- inside filter, retain, assert!, or a plain if. Writing if let Some(_) = opt { true } else { false } says the same thing in four times the space.

Let chains

Two let bindings and a condition can be chained with && inside one if:

if let Some(user) = &session.user
    && let Some(team) = &user.team
    && team.active
{
    println!("{} is on {}", user.name, team.name);
}

Each binding is in scope for the rest of the chain and for the block. This is stable from Rust 1.88, and only in edition 2024 -- on an older compiler or an older edition the same code needs one if let nested inside another, with the plain condition innermost. Check your edition in Cargo.toml before reaching for it, because the failure mode is a syntax error rather than anything descriptive.


Real World Example: Following a Redirect Chain

A site keeps a table of old paths and where they now point. Resolving a URL means following that table until it stops pointing anywhere, then looking up the page -- and both halves of that sentence are a pattern-with-a-binding.

enum Outcome {
    Found { path: String, title: String, hops: u32 },
    Missing { path: String },
    TooManyHops { last: String },
}

struct Site {
    redirects: Vec<(String, String)>,
    pages: Vec<(String, String)>,
}

impl Site {
    fn redirect_of(&self, path: &str) -> Option<&str> {
        self.redirects
            .iter()
            .find(|(from, _)| from.as_str() == path)
            .map(|(_, to)| to.as_str())
    }

    fn title_of(&self, path: &str) -> Option<&str> {
        self.pages
            .iter()
            .find(|(p, _)| p.as_str() == path)
            .map(|(_, t)| t.as_str())
    }

    fn resolve(&self, start: &str) -> Outcome {
        let mut path = start;
        let mut hops = 0;

        while let Some(next) = self.redirect_of(path) {
            hops += 1;
            if hops > 4 {
                return Outcome::TooManyHops { last: path.to_string() };
            }
            path = next;
        }

        let Some(title) = self.title_of(path) else {
            return Outcome::Missing { path: path.to_string() };
        };

        Outcome::Found {
            path: path.to_string(),
            title: title.to_string(),
            hops,
        }
    }
}

fn summary(o: &Outcome) -> String {
    match o {
        Outcome::Found { path, title, hops: 0 } => format!("{title} at {path}"),
        Outcome::Found { path, title, hops } => format!("{title} at {path} after {hops} hops"),
        Outcome::Missing { path } => format!("no page at {path}"),
        Outcome::TooManyHops { last } => format!("redirect loop, gave up at {last}"),
    }
}
fn main() {
    let site = Site {
        redirects: vec![
            (String::from("/old-home"), String::from("/home")),
            (String::from("/home"), String::from("/")),
            (String::from("/a"), String::from("/b")),
            (String::from("/b"), String::from("/c")),
            (String::from("/c"), String::from("/d")),
            (String::from("/d"), String::from("/e")),
            (String::from("/e"), String::from("/f")),
        ],
        pages: vec![
            (String::from("/"), String::from("Front page")),
            (String::from("/pricing"), String::from("Pricing")),
        ],
    };

    let starts = ["/", "/old-home", "/pricing", "/missing", "/a"];

    for s in starts {
        println!("{:<10} {}", s, summary(&site.resolve(s)));
    }

    println!();

    let mut indexed = 0;
    for s in starts {
        if let Outcome::Found { title, hops, .. } = site.resolve(s) {
            indexed += 1;
            println!("indexing {title} after {hops} hops");
        }
    }

    println!("\nindexed {indexed} of {} starts", starts.len());
}

Output:

/          Front page at /
/old-home  Front page at / after 2 hops
/pricing   Pricing at /pricing
/missing   no page at /missing
/a         redirect loop, gave up at /e

indexing Front page after 0 hops
indexing Front page after 2 hops
indexing Pricing after 0 hops

indexed 3 of 5 starts

The whole redirect walk is one while let. The loop's condition is the question "does this path point somewhere else?", and the binding next is the answer, in scope exactly where it is needed. The alternative -- loop, then match self.redirect_of(path), then Some(next) => path = next, then None => break -- is four more lines saying the same thing, and it puts the interesting assignment two levels deep. When a loop should run for as long as a lookup keeps succeeding, while let is not a shortcut, it is the direct statement.

let Some(title) = self.title_of(path) else { return ... }; is the precondition shape. Everything after it is the successful case, unindented, with title in scope as a plain &str. Written as if let, the final Outcome::Found construction would sit inside a block, and the Missing case -- the boring one -- would be the outer, visually dominant branch. let ... else inverts that: the failure exits early, and the reader's eye stays on the path that matters.

The last loop is where the choice becomes a design decision rather than a style preference. Indexing cares about exactly one outcome, so if let Outcome::Found { .. } is right, and the two ignored cases cost nothing -- no _ => {} arm, no comment explaining that nothing happens. Meanwhile summary is a match, because there all three outcomes have something to say. Now add a fourth variant, say Outcome::Gone: summary stops compiling and demands a decision, while the indexing loop keeps working and silently skips it. That asymmetry is the point. The reporting code must be revisited; the indexer genuinely should not care.

Three honest limits. redirect_of and title_of do a linear scan over a Vec<(String, String)>, which is fine for a handful of rules and wrong for a site map -- a HashMap is the real structure, and that is M4. The hop limit of 4 is arbitrary, and more importantly a limit cannot tell a long legitimate chain from a two-step cycle; a set of visited paths would report the loop honestly instead of guessing. And every Outcome allocates three Strings with to_string() where borrowed &str tied to the site's lifetime would do, which is the trade you make to keep Outcome free of lifetime parameters until M6.


Common Mistakes

  1. Reaching for if let where the unmatched case actually matters. This is the one mistake that costs money. if let Band::Letter { .. } = band { charge(85) } prices letters and silently charges nothing for everything else, and it will keep doing so after three more bands are added. Before writing if let, answer the question honestly: if a new variant appeared tomorrow, is doing nothing the correct behaviour? If the answer is no, you want a match.
  1. Expecting while let to skip the items that do not match. It stops at the first mismatch. while let Some(Some(n)) = items.pop() over [Some(1), None, Some(2)] sums the entries before the None and abandons the rest -- and the None itself has already been removed, because pop ran before the pattern was tested. When you want "skip and keep going", use a for loop with an if let inside, or .flatten().
  1. Using a binding after its block has ended. if let Some(port) = raw { } followed by println!("{port}") is error[E0425], "cannot find value in this scope". The binding exists only inside the block, which is exactly why let ... else exists: it puts the binding in the enclosing scope so the rest of the function can use it.
  1. Being surprised by deliberate shadowing. if let Some(config) = config { ... } is idiomatic, and inside the block config is the unwrapped payload while outside it is still the Option. That is fine when the block is three lines and confusing when it is thirty. Keep shadowed blocks short, or give the inner binding its own name when both meanings are live in the reader's head.
  1. Typing a variant name in lowercase. if let empty = slot { ... } does not test for Slot::Empty; it binds the whole slot to a new variable called empty and always runs the block. The irrefutable_let_patterns warning is the only signal, and it is easy to miss in a busy build. Import variants explicitly or write the full path so a typo is a name error rather than a new binding.
  1. Stacking if let three or four deep. Each level adds a brace, an indent, and a mental "and if that one failed?". Two levels is usually fine; at three, the honest options are a match on a tuple, a chain of let ... else preconditions, or -- on edition 2024 -- a let chain. The nesting is not a style crime, it is a signal that the code is asking several questions and pretending to ask one.
  1. Using if let to produce a value that a combinator already produces. if let Some(n) = opt { n * 2 } else { 0 } is opt.map_or(0, |n| n * 2). if let Some(n) = opt { n } else { 8080 } is opt.unwrap_or(8080). Neither combinator is shorter by accident: they say "transform or substitute" where the if let says "branch", and only one of those is what you meant.
  1. Writing if let Some(_) = opt as a boolean test. If you are not using the payload, you are asking a yes-or-no question, and opt.is_some() asks it directly. Where the question involves a pattern rather than a variant, matches! is the tool -- matches!(slot, Slot::Parcel { kg, .. } if kg > 10) reads as a predicate because it is one.
  1. Writing a let ... else whose else block does not diverge. let Some(port) = raw else { 8080 }; looks like it supplies a default and is rejected: the else block must return, break, continue, or panic, because there is no other way to leave port unbound. rustc says so directly, that the else clause does not diverge. If what you wanted was a default value, that is unwrap_or, not let ... else.

Best Practices

  • Use if let when exactly one shape matters and the others need nothing done. That is its whole job, and within that job it is clearer than a match with a _ => {} arm, because it does not give the ignored cases equal visual weight.
  • Switch to match the moment a second outcome needs its own behaviour. Two if let blocks in sequence over the same value, or an else if let chain three long, is a match that has not been written yet -- and the match gets you exhaustiveness for free.
  • Use let ... else for preconditions, so the happy path never indents. Three checks at the top of a function, each with a diverging else, leave the real work at one level. The same three as nested if let blocks leave it at four.
  • Prefer combinators for one-line value production. unwrap_or, unwrap_or_else, map_or and and_then express "substitute" and "transform" without a branch, and they compose where an if let does not.
  • Use matches! whenever the answer is a bool. Inside filter, retain, assert! or a plain if, it is both shorter and more honest than an if let whose only purpose is to reach true.
  • Match against a reference in if let unless the block must own the data. if let Some(text) = &raw leaves raw intact for the rest of the function; if let Some(text) = raw moves the payload out of any non-Copy Option.
  • Put a bound on any while let that follows data you do not control. Redirect chains, parent pointers and retry queues can all cycle. A hop counter is the cheap guard; a set of visited keys is the honest one, because it can tell you that there was a loop rather than only that you gave up.
  • Say out loud what silence means. When you choose if let over match on a type that will grow, that is a decision, and a one-line comment recording it ("new variants are deliberately not indexed") is worth more than the four lines the match would have cost.

Practice Exercises

  1. Watch exhaustiveness disappear. Take the Slot enum from the Syntax section and write fn fee(s: &Slot) -> u32 as an exhaustive match. Now rewrite it as an if let / else if let / else chain returning the same numbers, and confirm both versions agree on all three slots. Then add a fourth variant Slot::Pallet { kg: u32 } and compile both. Record which one failed, what it said, and what the other one now returns for a pallet.
  1. Stop versus skip. Write a function that sums the numbers in a Vec<Option<i32>> using while let Some(Some(n)) = list.pop(), and print both the sum and list.len() afterwards for the input [Some(1), None, Some(5), Some(2)]. Then write a second function producing the total of all the Some values in the same input without changing the data, and note which construct you had to reach for and why while let could not do it.
  1. Flatten with let ... else. Given struct Order { customer: Option<Customer> }, struct Customer { address: Option<Address> } and struct Address { postcode: Option<String> }, write fn postcode(o: &Order) -> String twice: once as three nested if let blocks with a fallback string, and once as three let ... else statements each returning early. Count the maximum indentation depth of both versions and the number of times the fallback string appears in each.
  1. Pick the right tool three times. For let slots: Vec<Slot>, write (a) a count of slots holding a parcel over 10 kg, (b) a Vec<u32> of every parcel id, and (c) a single line that reports whether any slot is a note. Use matches! for exactly one of them, if let inside a loop for exactly one, and a method on the iterator for the third -- then write two sentences justifying which went where.