How Do Closures Capture Variables in Rust?

Rust closures capture environment variables by borrowing or moving them into their own state based on usage.

Closures in Rust capture variables from their surrounding environment by borrowing or taking ownership of them, depending on how the closure is used. The compiler infers whether to borrow immutably, mutably, or move the variable into the closure's state based on the closure's usage of that variable.

fn main() {
    let x = 5;
    let equal_to_x = |z| z == x; // Captures `x` by immutable borrow
    println!("{}", equal_to_x(5));
}

If the closure needs to modify the captured variable, it captures it by mutable borrow. If the closure needs to own the variable (e.g., to move it to another thread), you must use the move keyword to force ownership transfer.