borrowing

Rust A closure can borrow surrounding data

A closure may capture a shared or mutable borrow of surrounding data, depending on how its body uses the data. A borrow captured by a closure can constrain access until the closure no longer needs it. Capturing by move is a distinct option. Expected output (not executed): 4 Why: The closure captures mutable access to stock; after its last call, stock can be read directly. Common mistake: Reading stock before a later call that still needs its exclusive capture.

Formal Syntax & Structure

rust syntaxrust
let action = || { ... };

Working Example

Example Snippetrust
fn main() {    let mut stock = 2;    let mut receive = || { stock += 1; };    receive();    receive();    println!("{stock}");}
Rust Reference