about summary refs log tree commit diff
path: root/src/doc/tutorial.md
diff options
context:
space:
mode:
authormdinger <mdinger.bugzilla@gmail.com>2014-04-19 03:21:01 -0400
committermdinger <mdinger.bugzilla@gmail.com>2014-04-19 03:21:01 -0400
commitb5809644ad6ee87dc28afd8200fa8e12213f4f29 (patch)
treefb100c4b6a7d4162e2a7c6c810acdee7b2587a11 /src/doc/tutorial.md
parentad0cdd7081bf78c4b7a00344f6f2b2f113cf0957 (diff)
downloadrust-b5809644ad6ee87dc28afd8200fa8e12213f4f29.tar.gz
rust-b5809644ad6ee87dc28afd8200fa8e12213f4f29.zip
Give more explanation when introducing closures
Diffstat (limited to 'src/doc/tutorial.md')
-rw-r--r--src/doc/tutorial.md36
1 files changed, 29 insertions, 7 deletions
diff --git a/src/doc/tutorial.md b/src/doc/tutorial.md
index 336f296ba25..ed70df7f3d3 100644
--- a/src/doc/tutorial.md
+++ b/src/doc/tutorial.md
@@ -1719,19 +1719,41 @@ environment). For example, you couldn't write the following:
 ~~~~ {.ignore}
 let foo = 10;
 
-fn bar() -> int {
-   return foo; // `bar` cannot refer to `foo`
-}
+// `bar` cannot refer to `foo`
+fn bar() -> () { println!("{}", foo); }
 ~~~~
 
 Rust also supports _closures_, functions that can access variables in
-the enclosing scope.
+the enclosing scope.  Compare `foo` in these:
+
+~~~~
+fn            bar() -> () { println!("{}", foo) }; // cannot reach enclosing scope
+let closure = |foo| -> () { println!("{}", foo) }; // can reach enclosing scope
+~~~~
+
+Closures can be utilized in this fashion:
 
 ~~~~
-fn call_closure_with_ten(b: |int|) { b(10); }
+// Create a nameless function and assign it to `closure`.
+// It's sole argument is a yet unknown `foo` to be supplied
+// by the caller.
+let closure = |foo| -> () { println!("{}", foo) };
+
+// Define `call_closure_with_ten` to take one argument and return null `()`.
+// `fun` is a function which takes one `int` argument `|int|` and also returns
+// null `()`.  `|int|` defines the `fun` to be of type _closure_
+fn call_closure_with_ten(fun: |int| -> ()) -> () { fun(10); }
 
-let captured_var = 20;
-let closure = |arg| println!("captured_var={}, arg={}", captured_var, arg);
+// The caller supplies `10` to the closure
+// which prints out the value
+call_closure_with_ten(closure);
+~~~~
+
+This can be simplified by removing null arguments:
+
+~~~~
+let closure = |foo| println!("{}", foo);
+fn call_closure_with_ten(fun: |int|) { fun(10); }
 
 call_closure_with_ten(closure);
 ~~~~