@@ -19,21 +19,23 @@ Other characteristics of closures include:
1919
2020``` rust,editable
2121fn main() {
22- // Increment via closures and functions.
23- fn function(i: i32) -> i32 { i + 1 }
22+ let outer_var = 42;
23+
24+ // A regular function can't refer to variables in the enclosing environment
25+ //fn function(i: i32) -> i32 { i + outer_var }
26+ // TODO: uncomment the line above and see the compiler error. The compiler
27+ // suggests that we define a closure instead.
2428
2529 // Closures are anonymous, here we are binding them to references
2630 // Annotation is identical to function annotation but is optional
2731 // as are the `{}` wrapping the body. These nameless functions
2832 // are assigned to appropriately named variables.
29- let closure_annotated = |i: i32| -> i32 { i + 1 };
30- let closure_inferred = |i | i + 1 ;
31-
32- let i = 1;
33- // Call the function and closures.
34- println!("function: {}", function(i));
35- println!("closure_annotated: {}", closure_annotated(i));
36- println!("closure_inferred: {}", closure_inferred(i));
33+ let closure_annotated = |i: i32| -> i32 { i + outer_var };
34+ let closure_inferred = |i | i + outer_var ;
35+
36+ // Call the closures.
37+ println!("closure_annotated: {}", closure_annotated(1));
38+ println!("closure_inferred: {}", closure_inferred(1));
3739 // Once closure's type has been inferred, it cannot be inferred again with another type.
3840 //println!("cannot reuse closure_inferred with another type: {}", closure_inferred(42i64));
3941 // TODO: uncomment the line above and see the compiler error.
0 commit comments