Closures in Rust
# Closures
inspired by ruby and smalltalk
closure is an anonymous function that can borrow or capture data from the scope it is nested in.
a parameter list between two pipes without type notions and the function between two curly braces.
|
|
A closure will borrow references to values in the enclosing scope. This creates an anonymous function you can call later.
|
|
you don’t need parameters.
|
|
closures can also take references to values in the current scope.
|
|
the compiler won’t let us move this to another thread because this might live longer than another thread. But there is move support for closures to remedy this.
|
|
this forces the closure to move any variables into itself and take ownership of them.
functional programming, closures will be your friend
1 2 3 4 5
let mut v = vec![2,4,6]; v.iter() .map(|x|x*3) .filter(|x|*x>10) .fold(0,|acc,x| acc+x);