@@ -1719,19 +1719,41 @@ environment). For example, you couldn't write the following:
1719
1719
~~~~ {.ignore}
1720
1720
let foo = 10;
1721
1721
1722
- fn bar() -> int {
1723
- return foo; // `bar` cannot refer to `foo`
1724
- }
1722
+ // `bar` cannot refer to `foo`
1723
+ fn bar() -> () { println!("{}", foo); }
1725
1724
~~~~
1726
1725
1727
1726
Rust also supports _closures_, functions that can access variables in
1728
- the enclosing scope.
1727
+ the enclosing scope. Compare `foo` in these:
1728
+
1729
+ ~~~~
1730
+ fn bar() -> () { println!("{}", foo) }; // cannot reach enclosing scope
1731
+ let closure = |foo| -> () { println!("{}", foo) }; // can reach enclosing scope
1732
+ ~~~~
1733
+
1734
+ Closures can be utilized in this fashion:
1729
1735
1730
1736
~~~~
1731
- fn call_closure_with_ten(b: |int|) { b(10); }
1737
+ // Create a nameless function and assign it to `closure`.
1738
+ // It's sole argument is a yet unknown `foo` to be supplied
1739
+ // by the caller.
1740
+ let closure = |foo| -> () { println!("{}", foo) };
1741
+
1742
+ // Define `call_closure_with_ten` to take one argument and return null `()`.
1743
+ // `fun` is a function which takes one `int` argument `|int|` and also returns
1744
+ // null `()`. `|int|` defines the `fun` to be of type _closure_
1745
+ fn call_closure_with_ten(fun: |int| -> ()) -> () { fun(10); }
1732
1746
1733
- let captured_var = 20;
1734
- let closure = |arg| println!("captured_var={}, arg={}", captured_var, arg);
1747
+ // The caller supplies `10` to the closure
1748
+ // which prints out the value
1749
+ call_closure_with_ten(closure);
1750
+ ~~~~
1751
+
1752
+ This can be simplified by removing null arguments:
1753
+
1754
+ ~~~~
1755
+ let closure = |foo| println!("{}", foo);
1756
+ fn call_closure_with_ten(fun: |int|) { fun(10); }
1735
1757
1736
1758
call_closure_with_ten(closure);
1737
1759
~~~~
0 commit comments