skip to content

In Rust, why does `let _ = pool.checkout();` release the guard at once while `let _conn = pool.checkout();` holds it until the block ends?

level: middleimportance: should knowfreq 40%

answer

  1. a pattern versus a variable
  2. the wildcard binds nothing
  3. temporary dies at the semicolon
  4. leading underscore only silences a lint

basics

~20 s

The wildcard pattern _ binds nothing, so the returned guard stays a temporary and is dropped at the end of the let statement. _conn is an ordinary variable, dropped at the end of its block; the underscore only silences the unused-variable lint.

solid answer

~40 s

`_` is the **wildcard pattern**, not a variable name: it matches the value without moving, copying or borrowing it. In `let _ = pool.checkout();` the call's result is therefore a temporary with nowhere to live, and an unborrowed temporary in a `let` initializer is dropped when that statement ends, so the connection goes straight back to the pool. `_conn` is an **identifier pattern** that creates a real variable; the leading underscore only tells the `unused_variables` lint you meant it, and the guard lives until the block ends. The same rule makes `let _ = named;` a no-op: nothing is moved, and `named` is dropped at its own scope end. Write `let _conn = ...` whenever the guard's lifetime is the point.

code

rust · 24 lines
rust
struct PoolGuard(u32);

impl Drop for PoolGuard {
    fn drop(&mut self) {
        println!("guard {} released", self.0);
    }
}

fn checkout(id: u32) -> PoolGuard {
    println!("guard {id} acquired");
    PoolGuard(id)
}

fn main() {
    let _ = checkout(1);
    println!("after let _");
    let _held = checkout(2);
    println!("after let _held");
    let named = checkout(3);
    let _ = named; // binds nothing, moves nothing
    println!("after let _ = named");
    checkout(4).0;
    println!("after a temporary in an expression statement");
}

go deeper

for a junior

Know that _ binds nothing while _name is a real variable, and that a guard you want to keep needs a name such as _guard.

for a middle

Explain temporary scopes: a value not moved into a variable lives until the end of its statement, which is why let _ releases a fresh guard but does nothing to an existing variable.

for a senior

Trace guard lifetimes in conditions and match scrutinees, catch let _ on guards in review, and turn on let_underscore_drop where a codebase depends on drop-time side effects.

for a principal

Decide whether guard-heavy code should enable let_underscore_drop crate-wide, weighing its noise on intentional discards against silent zero-length guards reaching production.

## Patterns, not names On the left of `let` sits a **pattern**. Most of the time it is an **identifier pattern** such as `conn` or `_conn`, which creates a new variable and moves (or copies) the value into it. The single underscore is different: `_` is the **wildcard pattern**. It matches any value and **binds nothing**: it does not move, copy or borrow what it matches. A name that merely starts with an underscore, like `_conn` or `_guard`, is still an ordinary identifier. The only thing the leading underscore changes is that the `unused_variables` lint stays quiet. The variable exists, owns the guard, and is dropped at the end of its block like any other local. ## Where the guard goes in each case | Statement | Is a variable created? | When the guard is dropped | |---|---|---| | `let _conn = pool.checkout();` | yes, `_conn` | end of the enclosing block | | `let _ = pool.checkout();` | no | end of this `let` statement | | `let _ = conn;` (existing variable) | no, and nothing moves | end of `conn`'s own scope | | `pool.checkout().run(sql);` | no | end of this statement | The second row follows from the rules for **temporaries**. A function call's result that is not moved into a variable lives in a temporary, and the Reference gives each temporary a **temporary scope**: the smallest enclosing scope among a statement, the body of an `if`, `while` or `loop`, a condition, a match arm and a few others. For a `let` initializer, that scope is the `let` statement itself, so the guard's destructor runs at the semicolon. The same rule releases the guard in the fourth row: the expression statement ends, and the temporary goes with it. One exception is **temporary lifetime extension**: when the initializer borrows the temporary, as in `let _ = &pool.checkout();`, the temporary is extended to the end of the block even though the pattern is the wildcard. Without the `&`, there is no extension. The third row is the one that surprises people from the other direction. Because the wildcard does not move anything, `let _ = conn;` does **not** release `conn`; it is a statement that does nothing at run time. Use `drop(conn)` to release a named guard early. ## Why this bites in production A pool guard, a temp-file wrapper or a transaction handle exists for its **side effect at drop time**. Writing `let _ = pool.checkout();` to "hold" a connection for a section of code silently holds it for zero statements. Typical symptoms: - a reservation that was meant to throttle concurrent work never throttles anything; - a temp file that should exist while a subprocess reads it is deleted before the subprocess starts; - a test that "holds" a resource passes for the wrong reason. The fix is always the same: give the guard a name for exactly as long as it must live. A useful house style makes intent visible at a glance: 1. `let _guard = ...;` when the value exists only for its drop-time effect and must last to the end of the block. 2. `drop(pool.checkout());` when an immediate release is genuinely intended, so a reader does not mistake it for a hold. 3. An inner block `{ let _guard = ...; ... }` when the hold should cover only part of a function. Nothing about `_guard` is special to the compiler; it is the name a reviewer recognises. ## What the compiler can and cannot tell you - Marking the guard type `#[must_use]` makes a bare `pool.checkout();` warn with `unused_must_use`. It does **not** catch `let _ = pool.checkout();`; rustc's own suggestion for silencing `must_use` is exactly `let _ = ...`. - The lint `let_underscore_drop` flags a non-binding `let` on a type with a destructor and suggests `let _unused = ...` or an explicit `drop(...)`, but it is **allow-by-default**; enable it with `#![warn(let_underscore_drop)]` if your codebase relies on guards. - A separate lint for standard library lock guards is deny-by-default; lock guards themselves belong with the material on threads. ## Temporaries in other positions The temporary rule has a few positions worth knowing. In `if pool.checkout().healthy() { ... }` the condition is its own temporary scope, so the guard is gone before the body runs. In `match pool.checkout().healthy() { ... }` the **scrutinee is not a temporary scope**, so the guard lives until the end of the whole `match` statement and is held while every arm runs. The 2024 edition also narrowed the temporary scope of block tail expressions and `if let` conditions; that change is covered with the 2024 edition itself.

  • In `match pool.checkout().healthy() { ... }`, is the guard still checked out while an arm runs?
    Yes. The scrutinee of a `match` is not a temporary scope, so the guard created there lives until the end of the whole `match` statement, through every arm. If an arm checks out again from a blocking pool of size one, it waits on itself. Bind the result first, `let ok = pool.checkout().healthy();`, then match on `ok`.
  • Does `#[must_use]` on the guard type stop someone writing `let _ = pool.checkout();`?
    No. `#[must_use]` warns when the value is discarded by a bare expression statement, and rustc's own help for that warning suggests `let _ = ...` to silence it. To flag the wildcard form, enable the allow-by-default `let_underscore_drop` lint.
  • What does `let _ = conn;` do to an existing guard variable `conn`?
    Nothing. The wildcard pattern matches without moving, so `conn` keeps ownership and is dropped at the end of its own scope. To release it early, call `drop(conn)`.

  • let _ = guard; releases an existing guard variable immediately.
  • _conn and _ both discard the value, since a leading underscore means unused.
  • Marking the guard type #[must_use] makes let _ = checkout() warn.
  • A temporary created in a match scrutinee is dropped before the arms run.
  • let _ = pool.checkout(); keeps the connection until the end of the block.