Pybites Logo Rust Platform

Closure Captures

Medium +3 pts

🎯 In Python, closures can read variables from their enclosing scope freely, but modifying them requires the nonlocal keyword:

def toggler():
    state = False
    def flip():
        nonlocal state
        state = not state
        return state
    return flip

t = toggler()
t()  # True
t()  # False

Without nonlocal, Python treats state as a new local variable and you get an UnboundLocalError. Rust handles this differently — through three capture modes and three closure traits.

Three ways to capture

Closures can capture variables from their environment in three ways:

By reference (&T) — default when the closure only reads:

let x = 5;
let read_x = || println!("{x}");  // borrows x
read_x();
println!("{x}");  // x still usable

Login to see the full exercise.