Let's make a closure:
-```{rust}
+```{rust,ignore}
let add_one = |x| { 1 + x };
println!("The sum of 5 plus 1 is {}.", add_one(5));
Let's compare syntax. The two are pretty close:
-```{rust}
+```{rust,ignore}
let add_one = |x: i32| -> i32 { 1 + x };
fn add_one (x: i32) -> i32 { 1 + x }
```
the name: a closure "closes over its environment." What does that mean? It means
this:
-```{rust}
+```{rust,ignore}
fn main() {
let x = 5;
Closures are most useful as an argument to another function. Here's an example:
-```{rust}
+```{rust,ignore}
fn twice(x: i32, f: |i32| -> i32) -> i32 {
f(x) + f(x)
}
Let's break the example down, starting with `main`:
-```{rust}
+```{rust,ignore}
let square = |x: i32| { x * x };
```
We've seen this before. We make a closure that takes an integer, and returns
its square.
-```{rust}
+```{rust,ignore}
# fn twice(x: i32, f: |i32| -> i32) -> i32 { f(x) + f(x) }
# let square = |x: i32| { x * x };
twice(5, square); // evaluates to 50
how the `|i32| -> i32` syntax looks a lot like our definition of `square`
above, if we added the return type in:
-```{rust}
+```{rust,ignore}
let square = |x: i32| -> i32 { x * x };
// |i32| -> i32
```
Okay, let's look at the body of `twice`:
-```{rust}
+```{rust,ignore}
fn twice(x: i32, f: |i32| -> i32) -> i32 {
f(x) + f(x)
}
If we didn't want to give `square` a name, we could just define it inline.
This example is the same as the previous one:
-```{rust}
+```{rust,ignore}
fn twice(x: i32, f: |i32| -> i32) -> i32 {
f(x) + f(x)
}
A named function's name can be used wherever you'd use a closure. Another
way of writing the previous example:
-```{rust}
+```{rust,ignore}
fn twice(x: i32, f: |i32| -> i32) -> i32 {
f(x) + f(x)
}
after the trait name, using the same syntax used in [generic
functions](#generic-functions).
-```
+``` ignore
trait Seq<T> {
fn len(&self) -> uint;
fn elt_at(&self, n: uint) -> T;
In this example, we define a function `ten_times` that takes a higher-order
function argument, and call it with a lambda expression as an argument.
-```
+``` ignore
fn ten_times(f: |int|) {
let mut i = 0;
while i < 10 {
An example of a `fn` type:
-```
+``` ignore
fn add(x: int, y: int) -> int {
return x + y;
}
An example of creating and calling a closure:
-```rust
+``` ignore
let captured_var = 10i;
let closure_no_args = || println!("captured_var={}", captured_var);