Define Rust closures with |args| body syntax and use move to take ownership of captured variables.
Define a closure using the |args| body syntax to create an anonymous function that can capture variables from its environment. Use the move keyword if you need the closure to take ownership of the captured values instead of borrowing them.
let x = 10;
let add_x = |n| n + x;
println!("{}", add_x(5));
let y = String::from("hello");
let consume_y = move || println!("{}", y);
consume_y();
A closure is a small, unnamed function that can remember variables from where it was created. Think of it like a helper tool that you hand to a worker, and it keeps a copy of the instructions and materials it needs right in its pocket. You use them to pass short logic blocks to other functions or to keep data around without global variables.