@@ -1717,27 +1717,32 @@ environment (sometimes referred to as "capturing" variables in their
1717
1717
environment). For example, you couldn't write the following:
1718
1718
1719
1719
~~~~ {.ignore}
1720
- let foo = 10 ;
1720
+ let x = 3 ;
1721
1721
1722
- // `bar ` cannot refer to `foo `
1723
- fn bar () -> () { println!("{}", foo ); }
1722
+ // `fun ` cannot refer to `x `
1723
+ fn fun () -> () { println!("{}", x ); }
1724
1724
~~~~
1725
1725
1726
1726
Rust also supports _closures_, functions that can access variables in
1727
- the enclosing scope. Compare `foo ` in these:
1727
+ the enclosing scope. Compare `x ` in these:
1728
1728
1729
1729
~~~~
1730
- fn bar() -> () { println!("{}", foo) }; // cannot reach enclosing scope
1731
- let closure = |foo| -> () { println!("{}", foo) }; // can reach enclosing scope
1730
+ let x = 3;
1731
+
1732
+ // `fun` is an invalid definition
1733
+ fn fun () -> () { println!("{}", x) }; // cannot reach enclosing scope
1734
+ let closure = || -> () { println!("{}", x) }; // can reach enclosing scope
1735
+
1736
+ fun(); // Still won't work
1737
+ closure(); // Prints: 3
1732
1738
~~~~
1733
1739
1734
1740
Closures can be utilized in this fashion:
1735
1741
1736
1742
~~~~
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) };
1743
+ // Create a nameless function and assign it to `closure`. It's sole
1744
+ // argument is a yet unknown `x` to be supplied by the caller.
1745
+ let closure = |x| -> () { println!("{}", x) };
1741
1746
1742
1747
// Define `call_closure_with_ten` to take one argument and return null `()`.
1743
1748
// `fun` is a function which takes one `int` argument `|int|` and also returns
@@ -1752,7 +1757,7 @@ call_closure_with_ten(closure);
1752
1757
This can be simplified by removing null arguments:
1753
1758
1754
1759
~~~~
1755
- let closure = |foo | println!("{}", foo );
1760
+ let closure = |x | println!("{}", x );
1756
1761
fn call_closure_with_ten(fun: |int|) { fun(10); }
1757
1762
1758
1763
call_closure_with_ten(closure);
0 commit comments