lifetime

Rust Rust 2024 if-let temporary drop scope

In edition 2024, temporaries created by the if-let scrutinee are destroyed before the else branch when the pattern fails. This matters when a temporary holds a resource or lock. The 2021 edition can retain those temporaries until after the whole if-let expression. Expected output (not executed): release fallback Why: The temporary Probe is dropped before else in edition 2024. The example uses a harmless marker instead of a real lock. Common mistake: Assuming the drop sequence is identical across editions or that a successful pattern drops all borrowed temporaries before the then branch.

Formal Syntax & Structure

rust syntaxrust
if let Some(value) = expression { ... } else { ... }

Working Example

Example Snippetrust
struct Probe;impl Probe { fn read(&self) -> Option<u8> { None } }impl Drop for Probe { fn drop(&mut self) { println!("release"); } }fn main() {    if let Some(value) = Probe.read() {        println!("{value}");    } else {        println!("fallback");    }}
Rust Reference