skip to content

In Rust, why is `match topics.lock().unwrap().get(&room).cloned() { Some(t) => notify(t).await, None => {} }` not `Send`, despite cloning the value out?

level: seniorimportance: should knowfreq 40%

answer

  1. the guard is a temporary
  2. scrutinee temporaries outlive the arms
  3. cloned copies the value, not the lock
  4. bind with let first
  5. 2024 if let and else

basics

~20 s

The MutexGuard returned by lock().unwrap() is a temporary in the match scrutinee, and such temporaries live until the match has finished. The guard is therefore still alive at notify(t).await, which makes the future not Send even though t is an owned clone.

solid answer

~40 s

`.cloned()` gives the arm an owned `String`, but it does nothing to the `std::sync::MutexGuard` temporary that `lock().unwrap()` produced on the way. Temporaries in a `match` scrutinee are dropped only after the `match` has finished, typically at the end of the enclosing statement, not when the scrutinee has been evaluated, so the guard is still alive at `notify(t).await`; the future stores it and is not `Send`. rustc says so directly: the note points at `topics.lock().unwrap()` and says the await occurs "with `topics.lock().unwrap()` maybe used later". The fix is to bind the result first, `let topic = topics.lock().unwrap().get(&room).cloned();`, because a temporary in a `let` statement dies at its semicolon. `if let` keeps the guard alive through its then-block too; since the 2024 edition, stable since Rust 1.85, it is dropped before the `else` block.

code

rust · 20 lines
rust
use std::collections::HashMap;
use std::sync::{Arc, Mutex};

type Topics = Arc<Mutex<HashMap<u32, String>>>;

async fn notify(topic: String) { let _ = topic; }

fn require_send<T: Send>(_: T) {}

async fn on_join(topics: Topics, room: u32) {
    // the MutexGuard temporary lives until the end of the whole match
    match topics.lock().unwrap().get(&room).cloned() {
        Some(t) => notify(t).await,
        None => {}
    }
}

fn main() {
    require_send(on_join(Arc::new(Mutex::new(HashMap::new())), 7));
}

go deeper

for a junior

Remember that a lock guard can exist without a name, and that putting lock() inside a match keeps it locked while the arms run.

for a middle

Explain the temporary-scope rules for let, statements, match and if let, and why the match rule exists, so a one-line lock can be read for how long it holds.

for a senior

Diagnose the non-Send future from the note that names the temporary, rewrite with a let binding, and know which edition moved the if let else drop so migrations are not surprised.

for a principal

Make the rule mechanical for the team: clippy in CI with await_holding_lock on, and a lock-then-bind style for anything that later awaits, so reviewers do not have to spot temporaries.

## The code that looks safe A chat server's join handler reads a room's topic from a `Arc<Mutex<HashMap<u32, String>>>` and sends it to the new member. Written as one expression, `match topics.lock().unwrap().get(&room).cloned() { Some(t) => notify(t).await, None => {} }`, it clones the topic out, so it seems no lock can be involved by the time `notify` runs. Spawning the handler on a multi-threaded executor still fails with "future cannot be sent between threads safely". ## Where the guard hides `topics.lock()` returns a `LockResult<MutexGuard<..>>`, and `.unwrap()` yields the `std::sync::MutexGuard`. Nothing binds the guard to a name: it is a **temporary**, a value created during expression evaluation. `.get(&room)` borrows through the guard, and `.cloned()` turns the `Option<&String>` into an owned `Option<String>`. The `String` is now independent of the lock, but the guard temporary still has to be dropped somewhere, and where is decided by **temporary scope rules**, not by whether anyone still needs it. ## What rustc tells you The error is the same `future cannot be sent between threads safely`, printed without an E-code, but the notes reveal that a temporary, not a binding, is at fault: 1. The `help` line names `std::sync::MutexGuard<'_, HashMap<u32, String>>` as the type that is not `Send`. 2. The note underlines the expression `topics.lock().unwrap()` where you would expect a variable name, saying it has a type "which is not `Send`". 3. It then marks the `.await` inside the arm: "await occurs here, with `topics.lock().unwrap()` maybe used later". An expression where a variable name should be means some enclosing construct is keeping a temporary alive, so the next question is which scope rule does it. ## The temporary-scope rules that matter | construct | temporaries from the scrutinee or initialiser are dropped | |---|---| | `let x = expr;` | at the end of the `let` statement | | `expr;` as a statement | at the end of the statement | | `match expr { .. }` | after the whole `match`, typically at the end of its enclosing statement | | `if let p = expr { .. }` | after the then-block, in every edition | | `if let p = expr { .. } else { .. }` | 2024 edition: before entering `else`; 2021: after the `else` too | The `match` rule exists because an arm may bind references into the scrutinee, so the temporaries have to outlive the arms. Since the `.await` sits inside an arm, the guard is alive there and becomes part of the future. The compiler's notes say exactly this, pointing at `topics.lock().unwrap()` as the value "used across an await". ## Fixes 1. **Bind first.** `let topic = topics.lock().unwrap().get(&room).cloned();` ends the guard at the semicolon; then `match topic { .. }` awaits with no lock held. This is the usual fix and it costs nothing. 2. **Use a block expression** when you want to keep it in one place: `let topic = { let map = topics.lock().unwrap(); map.get(&room).cloned() };`. 3. **Don't rely on `if let` to help** unless the await is in the `else` branch and the crate is on the 2024 edition; in the then-block the guard is alive in every edition. ## Why this matters beyond Send - The same rule causes a classic synchronous bug: locking the same mutex again inside a `match` arm whose scrutinee holds its guard, where std promises only that the second `lock()` will not return (it might panic or deadlock). - Clippy's `await_holding_lock`, in the `suspicious` group and warn by default, flags this exact shape, reporting "this `MutexGuard` is held across an await point" at the scrutinee; keeping clippy in CI catches it before a spawn does. - On migration, the `if_let_rescope` lint behind `cargo fix --edition` may rewrite an `if let` with a lock-guard temporary into a `match` to keep the 2021 drop point, which also keeps the guard alive through the old `else`; the material on the 2024 edition covers that lint. The diagnosis has one right answer once you know the rule: find the temporary, find the scope it belongs to, and move the lock into a statement that ends before the `.await`.

  • Would rewriting the `match` as `if let Some(t) = topics.lock().unwrap().get(&room).cloned() { notify(t).await; }` fix it?
    No. In every edition the scrutinee's temporaries stay alive while the then-block runs, so the guard is still held at the await and rustc 1.99.1 reports the same error. The 2024 edition only moved the drop before the `else` block; an await placed in `else` is then free of the guard, while in 2021 it was not.
  • How would you catch this pattern across a codebase before someone tries to spawn the handler?
    Run clippy in CI: `await_holding_lock` is warn-by-default in the `suspicious` group and flags guards held across an await even when they are scrutinee temporaries. For public async functions that must be spawnable, add a test that passes the future to a `require_send` helper so the build fails in the library itself.

  • .cloned() releases the lock because the value is now owned.
  • Scrutinee temporaries are dropped as soon as the match picks an arm.
  • Switching from match to if let fixes the then-branch await.
  • Only named bindings can be held across an .await.
  • Clippy cannot see a guard that has no variable name.

Assumes Rust 1.99 on the 2024 edition; since 1.85 that edition drops if let scrutinee temporaries before the else block, while match scrutinee temporaries are unchanged.