Skip to content

Commit bd6f972

Browse files
authored
[RFC 231] Capture mode and closure trait rules
I always have to open RFC 231 to check when i need to explain these rules to others So i copied these text (with minimal editorial changes) from RFC 231 to Reference so people can read them more easily.
1 parent f6185bb commit bd6f972

File tree

1 file changed

+18
-1
lines changed

1 file changed

+18
-1
lines changed

src/expressions/closure-expr.md

Lines changed: 18 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -34,9 +34,26 @@ closure can be forced to capture its environment by copying or moving values by
3434
prefixing it with the `move` keyword. This is often used to ensure that the
3535
closure's type is `'static`.
3636

37+
A. The capture modes of the free variables referenced by a closure without the `move`
38+
keyword are determined as follows:
39+
40+
1. Any variable which is closed over and borrowed mutably is by-reference and mutably borrowed.
41+
42+
2. Any variable of a type that does not implement `Copy` which is moved within the closure is captured by value.
43+
44+
3. Any other variable which is closed over is by-reference and immutably borrowed.
45+
46+
B. Free variables referenced by a `move ||` closure are always captured by value.
47+
3748
The compiler will determine which of the [closure
3849
traits](types.html#closure-types) the closure's type will implement by how it
39-
acts on its captured variables. The closure will also implement
50+
acts on its captured variables.
51+
52+
A. The trait that the unboxed closure implements is `FnOnce` if any variables were moved *out* of the closure; otherwise `FnMut` if there are any variables that are closed over and mutably borrowed; otherwise `Fn`.
53+
54+
B. The value returned by a `move ||` implements `FnOnce`, `FnMut`, or `Fn`, as determined above; thus, for example, `move |x: int, y| x + y` produces an unboxed closure that implements the `Fn(int, int) -> int` trait (and thus the `FnOnce(int, int) -> int` trait by inheritance).
55+
56+
The closure will also implement
4057
[`Send`](special-types-and-traits.html#send) and/or
4158
[`Sync`](special-types-and-traits.html#sync) if all of its captured types do.
4259
These traits allow functions to accept closures using generics, even though the

0 commit comments

Comments
 (0)