How closures capture variables

Rust closures capture variables from their defining scope by borrowing or moving them into their internal environment.

Closures capture variables from their surrounding scope by borrowing or taking ownership of them when they are defined. The compiler infers whether to borrow immutably, mutably, or move the value based on how the closure uses it, storing the captured data within the closure's environment. Use the move keyword to force the closure to take ownership of all captured variables immediately.

let x = 5;
let capture_borrow = || println!("x: {}", x);
let capture_move = move || println!("x: {}", x);