expression

Short guard scope: snapshot before expensive work

Copy or clone only the data required by work that does not need the lock. Release the guard before expensive processing. The snapshot can become stale, so do not treat it as current state without revalidation. Expected stdout (not executed): 12 4 Common mistake: Holding a guard while performing unrelated I/O or calling unknown callbacks.

Formal Syntax & Structure

rust syntaxrust
let snapshot = { lock.lock()?.clone() };

Working Example

Example Snippetrust
fn main() {    use std::sync::Mutex;    let m = Mutex::new(vec![2, 4, 6]);    let snapshot = { m.lock().unwrap().clone() };    m.lock().unwrap().push(8);    println!("{} {}", snapshot.iter().sum::<i32>(), m.lock().unwrap().len());}
Rust Reference