Sub topic 12
Temporaries and scope in edition 2024 if let
This chapter assumes you know if let ... else, ownership and borrowing, and how Drop and MutexGuard work. It covers one behavior change that edition 2024 made to if let. Your code compiles the same way, but values can be dropped at a different moment.
What a temporary is
A temporary is an unnamed value that Rust creates while it evaluates an expression. In make().get(), the value returned by make() is a temporary. Rust drops it at some point, and the language rules decide when.
Before edition 2024, a temporary in the scrutinee of an if let (the expression after =) lived until the end of the whole if let ... else statement. That included the else block, even though the else block can never use the matched bindings.
Seeing the difference
This program uses a type that prints when it is dropped:
struct Noisy(&'static str);
impl Drop for Noisy {
fn drop(&mut self) {
println!("drop {}", self.0);
}
}
impl Noisy {
fn get(&self) -> Option<u32> {
None
}
}
fn make() -> Noisy {
Noisy("guard")
}
fn main() {
if let Some(n) = make().get() {
println!("got {n}");
} else {
println!("else branch");
}
println!("after");
}The output depends on the edition set in Cargo.toml:
| Edition | Output order |
|---|---|
| 2021 and earlier | `else branch`, `drop guard`, `after` |
| 2024 | `drop guard`, `else branch`, `after` |
In edition 2024, temporaries from the scrutinee are dropped before the else block runs. When the pattern matches, they still live to the end of the then block, because the bindings may borrow from them.
Why this matters: locks
The change matters most when the temporary holds a resource. A MutexGuard returned by lock() is a common case.
use std::sync::Mutex;
fn main() {
let cache = Mutex::new(Vec::<u32>::new());
if let Some(first) = cache.lock().unwrap().first().copied() {
println!("first is {first}");
} else {
cache.lock().unwrap().push(1);
println!("cache was empty, added 1");
}
}The guard from the first lock() is a temporary in the scrutinee. In edition 2021 it is still held when the else block calls lock() again, so the program deadlocks or panics. Mutex is not reentrant. In edition 2024 the guard is dropped before the else block, and the program prints cache was empty, added 1.
Rules that stay the same
- When the pattern matches, temporaries in the scrutinee live through the
thenblock. This lets bindings borrow from them safely. - The rule also applies to
else if letchains. Each scrutinee's temporaries are dropped before the next branch is tried. - Let chains exist only in edition 2024, so they always use the new rule.
matchis unchanged. Its scrutinee temporaries still live to the end of the wholematch.
Moving a crate from 2021 to 2024
Run cargo fix --edition to migrate. The if_let_rescope lint, part of the rust_2024_compatibility group, flags places where the drop order changes and the difference could be observed. Review those spots, especially ones involving locks, RefCell borrows, or types with meaningful Drop side effects.
To make the order explicit in either edition, bind the value first so you control its lifetime:
use std::sync::Mutex;
fn main() {
let cache = Mutex::new(Vec::<u32>::new());
let first = cache.lock().unwrap().first().copied();
if let Some(first) = first {
println!("first is {first}");
} else {
cache.lock().unwrap().push(1);
println!("cache was empty, added 1");
}
}The guard is dropped at the end of the let statement, so this version works in every edition.
Exercise
A crate on edition 2021 has if let Some(v) = state.borrow().get(&key) { ... } else { state.borrow_mut().insert(key, 0); }, where state is a RefCell<HashMap<..>>. What goes wrong, and how does moving to edition 2024 change it?
Show answer
In edition 2021 the Ref from borrow() is a temporary that lives through the else block. The borrow_mut() call then panics with "already borrowed". In edition 2024 the Ref is dropped before the else block runs, so the borrow_mut() succeeds. In either edition, you can avoid the problem by evaluating the lookup into a local variable before the if let.