Closures
A closure is a function that captures variables from its surrounding scope. This means the function can remember and access those variables even after the outer function has finished executing. Closures are useful for creating factory functions, maintaining state, and implementing data hiding.
Closures are a powerful feature that enable advanced programming patterns and encapsulation.
Example
# Returns a function that captures its environment
fn make_adder(x: Int) {
return fn(y) => x + y
}
let add5 = make_adder(5)
print(add5(10)) # Should print 15
Let's break down how this example works:
make_adder
is a function that takes a numberx
as its input.- Inside
make_adder
, a new function is created and returned. This new function takes a numbery
as its input and adds it tox
. - When you call
make_adder(5)
, you get back a function that always adds 5 to its input. This returned function "remembers" the value ofx
(which is 5) even aftermake_adder
has finished running. That's what makes it a closure. - When you call
add5(10)
, it adds 10 (the value ofy
) to 5 (the remembered value ofx
), resulting in 15.
This shows how closures let functions keep information from their creation context and use it later.