Closures

Closures in Rust, also called lambda expressions or lambdas, are functions that can capture
the enclosing environment. For example, a closure that captures the x
variable:

  1. |val| val + x

The syntax and capabilities of closures make them very convenient for
on the fly usage. Calling a closure is exactly like calling a function.
However, both input and return types can be inferred and input
variable names must be specified.

Other characteristics of closures include:

  • using || instead of () around input variables.
  • optional body delimination ({}) for a single expression (mandatory otherwise).
  • the ability to capture the outer environment variables.
  1. fn main() {
  2. // Increment via closures and functions.
  3. fn function (i: i32) -> i32 { i + 1 }
  4. // Closures are anonymous, here we are binding them to references
  5. // Annotation is identical to function annotation but is optional
  6. // as are the `{}` wrapping the body. These nameless functions
  7. // are assigned to appropriately named variables.
  8. let closure_annotated = |i: i32| -> i32 { i + 1 };
  9. let closure_inferred = |i | i + 1 ;
  10. let i = 1;
  11. // Call the function and closures.
  12. println!("function: {}", function(i));
  13. println!("closure_annotated: {}", closure_annotated(i));
  14. println!("closure_inferred: {}", closure_inferred(i));
  15. // A closure taking no arguments which returns an `i32`.
  16. // The return type is inferred.
  17. let one = || 1;
  18. println!("closure returning one: {}", one());
  19. }