You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
A *closure expression*, also known as a lambda expression or a lambda, defines a [closure type] and evaluates to a value of that type.
16
-
The syntax for a closure expression is an optional `move` keyword, then a pipe-symbol-delimited (`|`) comma-separated list of [patterns], called the *closure parameters* each optionally followed by a `:` and a type, then an optional `->` and type, called the *return type*, and then an expression, called the *closure body operand*.
17
+
The syntax for a closure expression is an optional `async` keyword, an optional `move` keyword, then a pipe-symbol-delimited (`|`) comma-separated list of [patterns], called the *closure parameters* each optionally followed by a `:` and a type, then an optional `->` and type, called the *return type*, and then an expression, called the *closure body operand*.
17
18
The optional type after each pattern is a type annotation for the pattern.
18
19
If there is a return type, the closure body must be a [block].
19
20
@@ -29,10 +30,19 @@ This is often used to ensure that the closure's lifetime is `'static`.
29
30
30
31
## Closure trait implementations
31
32
32
-
Which traits the closure type implement depends on how variables are captured and the types of the captured variables.
33
+
Which traits the closure type implement depends on how variables are captured, the types of the captured variables, and the presence of `async`.
33
34
See the [call traits and coercions] chapter for how and when a closure implements `Fn`, `FnMut`, and `FnOnce`.
34
35
The closure type implements [`Send`] and [`Sync`] if the type of every captured variable also implements the trait.
35
36
37
+
## Async closures
38
+
39
+
When a closure is marked with the `async` keyword, it is allowed to `await` futures in its body.
40
+
Calling the closure evaluates to a future that corresponds to the computation of the body of the closure.
41
+
This closure implements `AsyncFn`, `AsyncFnMut`, and `AsyncFnOnce` depending on the use of the captured variables in its body.
42
+
It may also implement `Fn`, `FnMut`, and `FnOnce` if the future it returns does not borrow any captured variables from the closure itself.
43
+
44
+
> **Edition differences**: Async closures are only available beginning with Rust 2018.
45
+
36
46
## Example
37
47
38
48
In this example, we define a function `ten_times` that takes a higher-order function argument, and we then call it with a closure expression as an argument, followed by a closure expression that moves values from its environment.
0 commit comments