Functions

Rust Closures

Rust Closures

Rust closures capture variables with Fn FnMut and FnOnce traits.

Introduction to Rust Closures

Closures in Rust are anonymous functions you can save in a variable or pass as arguments to other functions. They are similar to functions, but with the capability to capture variables from their surrounding environment. Closures are flexible and can be used where function pointers are expected.

Capturing Variables in Closures

Rust closures can capture variables from their environment in three different ways, determined by the traits Fn, FnMut, and FnOnce. Depending on how a closure captures variables, it can be called more than once or only once.

Understanding Fn, FnMut, and FnOnce

  • Fn: The closure captures variables by reference, meaning it can be called multiple times without consuming the captured variables.
  • FnMut: The closure captures variables by mutable reference, allowing modification of the captured variables and can be called multiple times.
  • FnOnce: The closure captures variables by value, consuming the captured variables, and can be called only once.

Example: Fn Trait

In this example, the closure captures a variable by reference, allowing it to be called multiple times.

Example: FnMut Trait

This example demonstrates a closure that captures a variable by mutable reference. Note that the closure can modify the variable.

Example: FnOnce Trait

Here, the closure captures a variable by value, consuming it. The closure can only be called once.

Conclusion

Rust closures provide a powerful way to work with functions and captured variables. By understanding the differences between Fn, FnMut, and FnOnce, developers can effectively use closures to create flexible and efficient Rust programs.

Previous
Functions