// here the FnMut is being returned. So the vars (zz and dd) // need to live longer than the stack frame that contains them // to get this, "move" copies the variables from the stack to the // heap. fn main_2() { let mut r = make_fn(2); println!("{}", r()); println!("{}", r()); println!("{}", r()); } fn make_fn(inp:i32) -> impl FnMut() -> i32 { let mut zz = vec![inp]; let mut dd = inp + 4; let zp: u64 = &zz as *const Vec as u64; println!("zp (stack) {zp}"); let f = move || { zz.push(dd); dd += 2; let zp: u64 = &zz as *const Vec as u64; println!("zp (heap) {zp} {:?}", zz); return zz.len() as i32; }; //println!("zz {:?}", zz); f } // create a FnMut and pass it to another function // can pass the closure here because the function in which the // the closed variables exists remains on the stack, so those vars // exist at least as long as the function fn main_1() { let mut x: usize = 1; println!("Before {x}"); let add_two_to_x = || x += 2; do_repeatedly(add_two_to_x, 5); println!("After {x}"); } fn do_repeatedly(mut func: impl FnMut(), count:usize) { for i in 0..count { func(); } } fn main() { main_2(); }