Skip to content

Commit b580964

Browse files
committed
Give more explanation when introducing closures
1 parent ad0cdd7 commit b580964

File tree

1 file changed

+29
-7
lines changed

1 file changed

+29
-7
lines changed

src/doc/tutorial.md

Lines changed: 29 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1719,19 +1719,41 @@ environment). For example, you couldn't write the following:
17191719
~~~~ {.ignore}
17201720
let foo = 10;
17211721
1722-
fn bar() -> int {
1723-
return foo; // `bar` cannot refer to `foo`
1724-
}
1722+
// `bar` cannot refer to `foo`
1723+
fn bar() -> () { println!("{}", foo); }
17251724
~~~~
17261725
17271726
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:
17291735
17301736
~~~~
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); }
17321746
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); }
17351757
17361758
call_closure_with_ten(closure);
17371759
~~~~

0 commit comments

Comments
 (0)