3 Closures are functions that can capture the enclosing environment. For
4 example, a closure that captures the x variable:
10 The syntax and capabilities of closures make them very convenient for
11 on the fly usage. Calling a closure is exactly like calling a function.
12 However, both input and return types *can* be inferred and input
13 variable names *must* be specified.
15 Other characteristics of closures include:
16 * using `||` instead of `()` around input variables.
17 * optional body delimination (`{}`) for a single expression (mandatory otherwise).
18 * the ability to capture the outer environment variables.
22 // Increment via closures and functions.
23 fn function(i: i32) -> i32 { i + 1 }
25 // Closures are anonymous, here we are binding them to references
26 // Annotation is identical to function annotation but is optional
27 // as are the `{}` wrapping the body. These nameless functions
28 // are assigned to appropriately named variables.
29 let closure_annotated = |i: i32| -> i32 { i + 1 };
30 let closure_inferred = |i | 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));
38 // A closure taking no arguments which returns an `i32`.
39 // The return type is inferred.
41 println!("closure returning one: {}", one());