🦀 Rust Beginner

What are closures in Rust?

Answer

Closures in Rust are anonymous functions that can capture variables from their enclosing scope. The syntax is |params| expression or |params| { body }. Rust closures implement one of three traits depending on how they capture the environment: FnOnce (can be called once, consumes captured variables — every closure implements this), FnMut (can be called multiple times, mutably borrows captured variables), Fn (can be called any number of times, immutably borrows captured variables). Closures are passed to iterator methods like map(), filter(), and fold(). The move keyword forces a closure to take ownership of all captured variables, which is necessary for closures passed to threads.