Skip to content

Commit 36f98fb

Browse files
committed
Demonstrate accessing external variable in first example
1 parent b580964 commit 36f98fb

File tree

1 file changed

+16
-11
lines changed

1 file changed

+16
-11
lines changed

src/doc/tutorial.md

Lines changed: 16 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1717,27 +1717,32 @@ environment (sometimes referred to as "capturing" variables in their
17171717
environment). For example, you couldn't write the following:
17181718
17191719
~~~~ {.ignore}
1720-
let foo = 10;
1720+
let x = 3;
17211721
1722-
// `bar` cannot refer to `foo`
1723-
fn bar() -> () { println!("{}", foo); }
1722+
// `fun` cannot refer to `x`
1723+
fn fun() -> () { println!("{}", x); }
17241724
~~~~
17251725
17261726
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:
17281728
17291729
~~~~
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
17321738
~~~~
17331739
17341740
Closures can be utilized in this fashion:
17351741
17361742
~~~~
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) };
17411746
17421747
// Define `call_closure_with_ten` to take one argument and return null `()`.
17431748
// `fun` is a function which takes one `int` argument `|int|` and also returns
@@ -1752,7 +1757,7 @@ call_closure_with_ten(closure);
17521757
This can be simplified by removing null arguments:
17531758
17541759
~~~~
1755-
let closure = |foo| println!("{}", foo);
1760+
let closure = |x| println!("{}", x);
17561761
fn call_closure_with_ten(fun: |int|) { fun(10); }
17571762
17581763
call_closure_with_ten(closure);

0 commit comments

Comments
 (0)