Git repo: https://github.com/caveofprogramming/rust/
Basic Closures
The thing that the Rust docs call closures, at least as far as I can tell, are the same things that programmers in other languages call lambda expressions: simply-defined anonymous functions that can access the scope in which they’re defined.
Here’s an example of a closure that, when called, prints “Hello”.
The two vertical pipes provide a space where parameters can be defined.
This closure adds two numbers together. The expression provides the return value.
It is possible to supply explicit parameter and return types.
Now I’m forced to add in braces to get it to work.
Otherwise, the parameter and return types are inferred when you first call the closure.
Closure Type Inference
Here, I define a closure and pass an int to it. When I try to call it again with a float, I get an error, because the first call caused i32 to be inferred for the type of the parameter.
Accessing Local Variables within Closures
Closures can access variables in the enclosing scope (hence the name “closure”), either by immutable borrow, mutable borrow or by taking ownership.
This closure performs an immutable borrow:
Here’s a closure that performs a mutable borrow:
Passing Closures to Functions
To define a function parameters type that will accept a function or other closure, we can use the fn keyword.
This function accepts three parameters: a function that accepts two integers and returns an integers, and two integers.
We can call it like this:
This prints “11”.