I have recently become interested in closures and their usage in Rust, primarily because I have spent the past few weeks learning about and building web servers. When I first learned about closures and how to share objects between tasks (invoked functions, spawned threads), I found it helpful to think about these guides:
The lexical scope and the nesting of functions within an enclosing function.
Nested function(s) - named or anonymous - defined in the enclosing function.
Variables are scoped to the enclosing function, accessible to the nested function, and shared between the enclosing and enclosed functions.
The variables accessed by the closures are not copied by the closure. These variables are kept alive (on the heap) even after their enclosing function has been popped off the stack. Any updates to the variables will be reflected across the closures accessing them.
Some of these hold in Rust (somewhat), however, there are nuances to be considered, especially regarding ownership rules. In this article I try to outline what I have learned about closures in the past week, focusing on:
what closures are