]> git.proxmox.com Git - rustc.git/blob - src/doc/rust-by-example/src/fn/closures.md
New upstream version 1.51.0+dfsg1
[rustc.git] / src / doc / rust-by-example / src / fn / closures.md
1 # Closures
2
3 Closures are functions that can capture the enclosing environment. For
4 example, a closure that captures the x variable:
5
6 ```Rust
7 |val| val + x
8 ```
9
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.
14
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.
19
20 ```rust,editable
21 fn main() {
22 // Increment via closures and functions.
23 fn function(i: i32) -> i32 { i + 1 }
24
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 ;
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));
37
38 // A closure taking no arguments which returns an `i32`.
39 // The return type is inferred.
40 let one = || 1;
41 println!("closure returning one: {}", one());
42
43 }
44 ```