In Rust, a closure is an anonymous function that can capture variables from its surrounding environment. To create a closure, we use the |args| body
syntax, where args
is the list of arguments for the closure, and body
is the code that the closure executes.
Here's an example of a closure that adds two numbers together:
main.rs63 chars3 lines
In this example, we defined a closure called sum
that takes two arguments a
and b
, and returns their sum. We then called this closure with the arguments 4
and 5
, and assigned the result to the variable result
.
Closures can also capture variables from their surrounding environment. This is done using the move
keyword, like this:
main.rs81 chars4 lines
In this example, we defined a closure called square_x
that captures the variable x
from its surrounding environment. We then called this closure with no arguments, and assigned the result to the variable result
. Since x
was captured by value (using the move
keyword), we can still access it even though it's outside the closure's scope.
gistlibby LogSnag