Sub topic 12
Temporaries and scope in edition 2024 if let
This chapter assumes you know if let ... else, Option and Result, ownership and borrowing, and what a Drop implementation does. You should also have read the earlier chapters on if let, else, and let chains.
Edition 2024 changed one detail of if let: when the temporary values created in the scrutinee are dropped. The change is small, but it affects locks, RefCell borrows, and any other value whose drop has a visible effect.
What a temporary is
A temporary is a value that an expression creates but never stores in a variable. In slot.lock().unwrap(), the MutexGuard is a temporary. The guard releases the lock when it is dropped, so when it is dropped matters.
Rust drops a temporary at the end of the enclosing "temporary scope". For a plain statement like foo(make_guard());, that scope is the statement. For if let, the scrutinee is the expression after =, and it sits in a larger construct. The question is how long its temporaries live.
The rule before edition 2024
In editions 2021 and earlier, temporaries in the scrutinee of if let lived until the end of the whole if let ... else ... expression. That included the else block, even though the else block only runs when the pattern did not match.
The following program makes the order visible:
struct Guard(&'static str);
impl Drop for Guard {
fn drop(&mut self) {
println!("drop {}", self.0);
}
}
impl Guard {
fn value(&self) -> Option<i32> {
None
}
}
fn main() {
if let Some(v) = Guard("scrutinee").value() {
println!("then {v}");
} else {
println!("else block");
}
}Guard("scrutinee") is a temporary. The method value borrows it and returns None, so the else branch runs. The output depends on the edition:
| Edition | Output, in order |
|---|---|
| 2021 | `else block`, then `drop scrutinee` |
| 2024 | `drop scrutinee`, then `else block` |
In 2021 the guard is still alive while the else block runs. In 2024 it is already gone.
The rule in edition 2024
In edition 2024, temporaries in an if let scrutinee are dropped before the else block starts. If the pattern matches, they stay alive until the end of the then block, as before. The then block needs them because bindings often borrow from them.
Why it matters: the lock example
The classic failure is a mutex locked in the scrutinee and locked again in the else branch.
use std::sync::Mutex;
fn main() {
let slot: Mutex<Option<i32>> = Mutex::new(None);
if let Some(v) = *slot.lock().unwrap() {
println!("have {v}");
} else {
*slot.lock().unwrap() = Some(7);
println!("filled slot");
}
println!("{:?}", *slot.lock().unwrap());
}The first lock() creates a MutexGuard temporary. The pattern Some(v) copies the i32 out of the Option, so nothing needs the guard after the match test. In edition 2024 the guard is dropped before the else block, so the second lock() succeeds. The program prints filled slot and then Some(7).
In edition 2021 the same code locks the mutex twice on one thread. Mutex is not reentrant, so the second lock() may deadlock or panic. The standard library documents both outcomes as possible.
The workaround for older editions
If you must stay on edition 2021, take the value out of the lock first, so the guard's temporary scope is a plain let statement.
use std::sync::Mutex;
fn main() {
let slot: Mutex<Option<i32>> = Mutex::new(None);
let current = *slot.lock().unwrap();
if let Some(v) = current {
println!("have {v}");
} else {
*slot.lock().unwrap() = Some(7);
println!("filled slot");
}
println!("{:?}", *slot.lock().unwrap());
}Here the guard is dropped at the end of the let current = ...; statement. This version behaves the same in every edition. It is also a good habit when you want the lock held for as short a time as possible.
What did not change
The edition 2024 change is narrow. Several nearby rules stay as they were.
- The
thenblock. Temporaries in the scrutinee live through the wholethenblock when the pattern matches. This is whyif let Some(x) = map.lock().unwrap().get(&key) { ... }still works:xborrows from the guard, and the guard outlives the block that usesx. match. Temporaries in amatchscrutinee live until the end of the wholematchexpression, in every edition. Amatchon*slot.lock().unwrap()still holds the lock in every arm.while let. There is noelseblock. Temporaries in the scrutinee are dropped at the end of each iteration, in every edition.let else. Temporaries from the initializer are dropped before theelseblock runs. Theelseblock must diverge, so it never reaches the code after the statement.
| Construct | When scrutinee temporaries are dropped |
|---|---|
| `if let`, pattern matches | End of the `then` block, all editions |
| `if let`, pattern does not match | Before `else` in 2024. After `else` in 2021 and earlier |
| `match` | End of the whole `match`, all editions |
| `while let` | End of each iteration, all editions |
| `let else`, pattern does not match | Before the `else` block runs |
Let chains and temporaries
Let chains are available only in edition 2024, so they always use the new rule. Each let in a chain can create temporaries. If any link fails, the else block runs, and the temporaries from the links that were evaluated are already dropped by then.
use std::sync::Mutex;
fn main() {
let slot: Mutex<Option<i32>> = Mutex::new(Some(3));
if let Some(v) = *slot.lock().unwrap()
&& v > 5
{
println!("large value {v}");
} else {
*slot.lock().unwrap() = Some(0);
println!("reset slot");
}
println!("{:?}", *slot.lock().unwrap());
}The pattern matches with v = 3, but v > 5 is false, so the chain fails and the else block runs. The guard from the first link has already been dropped, so the second lock() is safe. This requires Rust 1.88 or newer and edition = "2024" in Cargo.toml.
Migrating an existing crate
Moving a crate from edition 2021 to 2024 can change where Drop side effects occur in if let ... else code. The compiler can find the affected places for you.
- Run
cargo fix --edition. It applies mechanical changes for the new edition. - The lint
if_let_rescopepoints atif letexpressions whose scrutinee has a temporary with a meaningfulDrop, and whose behavior may differ between editions. It is part of therust-2024-compatibilitylint group. When it fires,cargo fixcan rewrite the code into an equivalentmatch, which keeps the old drop order. - After changing
editioninCargo.toml, review each reported site. Most can use the new behavior as is. Keep the old behavior only if the code needs the temporary alive in theelseblock.
Common mistakes
- Assuming
matchchanged too. It did not. If you rewrite anif let ... elseas amatchto keep the old order, the temporaries then live for the wholematch. - Holding a lock across the
elsebranch by accident on 2021. Copy the value out with a separateletfirst, as in the workaround above. - Expecting temporaries to be dropped before the
thenblock. They live through it. Bindings may borrow from them, so Rust cannot drop them earlier. - Checking only the compiler version. The behavior depends on the edition in
Cargo.toml, not on the toolchain. A new compiler still follows 2021 rules for a 2021 crate.
Exercise
A crate on edition 2021 contains if let Some(v) = *cache.lock().unwrap() { use_value(v); } else { *cache.lock().unwrap() = Some(1); } where cache is a Mutex<Option<i32>>. It may hang. Why does it hang in 2021, what happens after moving to edition 2024, and how can you fix it without changing the edition?
Show answer
In 2021, the MutexGuard temporary from the scrutinee lives until the end of the whole if let ... else, so the else block calls lock() while the same thread still holds the lock. Mutex is not reentrant, so this can deadlock. In 2024, the guard is dropped before the else block runs, so the second lock() succeeds. To fix it on 2021, copy the value out first with let current = *cache.lock().unwrap(); and then use if let Some(v) = current { ... } else { ... }. The guard is dropped at the end of the let statement.
Exercise
For each construct, say whether its scrutinee temporaries are still alive while the else block runs in edition 2024: if let, match (in a non-matching arm), and let else.
Show answer
if let: no, they are dropped before the else block. match: yes, temporaries in the scrutinee live until the end of the whole match, so they are still alive inside any arm. let else: no, the initializer's temporaries are dropped before the else block runs.