How to Define and Use Closures in Rust

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();