# Closures in Rust ## Capturing only select variables ```rust fn closures() { let mut a = 10; let b = Box::new(20); let handle = |ab: &mut i32, b| { println!("{:?}", b); *ab += 10; println!("Hello from a thread - {}", ab); }; handle(&mut a, b); // mutable borrow of a, move the box println!("{}", a) } ``` ## Capturing all variables in closure **only variables that were used are captured** ```rust fn closures() { let mut a = 10; let mut b = Box::new(20); // create a mut box let r = b.as_mut(); // create a mutable ref, to pass to closure, only one mutable reference let c = Box::new(300); let ref_c = c.as_ref(); // or &c remember to pass only reference to closure for using later let mut handle = move || { // you should create references beforehand, if you want to pass as reference and use them later *r += 30; // only the mutable ref is moved here, b is fine outside chilling, can be used a += 20; println!("Hello from a closure - {}", a); println!("Immutable box borrowed as ref - {}", *ref_c) }; handle(); println!("{}", a); // a is 10, because a implements Copy, and that Copy is moved into closure println!("{}", b); println!("Immutable box {}", c); } ```