lifetime

Rust Rust 2024 block tail temporary scope

In edition 2024, a temporary created by a block tail expression may be destroyed before the block local variables. This can prevent a borrowed guard from outliving a local owner. It does not mean all tail expressions can return references to local values. Expected output (not executed): probe owner 7 Why: The borrowed temporary Probe is dropped at the tail expression scope before the owner in edition 2024. The result is an owned u8. Common mistake: Assuming older editions use the same tail temporary scope.

Formal Syntax & Structure

rust syntaxrust
let result = { owner.method() };

Working Example

Example Snippetrust
struct Owner;struct Probe<'a>(&'a Owner);impl Drop for Owner { fn drop(&mut self) { println!("owner"); } }impl Drop for Probe<'_> { fn drop(&mut self) { let _ = self.0; println!("probe"); } }impl Owner { fn probe(&self) -> Probe<'_> { Probe(self) } }impl Probe<'_> { fn value(&self) -> u8 { 7 } }fn main() {    let value = {        let owner = Owner;        owner.probe().value()    };    println!("{value}");}
Rust Reference