Skip to content

Commit fdaa801

Browse files
authored
Merge pull request #61 from est31/master
Document closure to fn coercion feature
2 parents e3479cb + 4c475e0 commit fdaa801

File tree

2 files changed

+20
-3
lines changed

2 files changed

+20
-3
lines changed

src/type-coercions.md

+5-1
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,10 @@
11
# Type coercions
22

3-
Coercions are defined in [RFC 401]. A coercion is implicit and has no syntax.
3+
Coercions are defined in [RFC 401]. [RFC 1558] then expanded on that.
4+
A coercion is implicit and has no syntax.
45

56
[RFC 401]: https://github.com/rust-lang/rfcs/blob/master/text/0401-coercions.md
7+
[RFC 1558]: https://github.com/rust-lang/rfcs/blob/master/text/1558-closure-to-fn-coercion.md
68

79
## Coercion sites
810

@@ -143,3 +145,5 @@ Coercion is allowed between the following types:
143145
In the future, coerce_inner will be recursively extended to tuples and
144146
structs. In addition, coercions from sub-traits to super-traits will be
145147
added. See [RFC 401] for more details.
148+
149+
* Non capturing closures to `fn` pointers

src/types.md

+15-2
Original file line numberDiff line numberDiff line change
@@ -286,9 +286,22 @@ more of the closure traits:
286286
* `Fn`
287287
: The closure can be called multiple times through a shared reference.
288288
A closure called as `Fn` can neither move out from nor mutate values
289-
from its environment. `Fn` inherits from `FnMut`, which itself
290-
inherits from `FnOnce`.
289+
from its environment, but read-only access to such values is allowed.
290+
`Fn` inherits from `FnMut`, which itself inherits from `FnOnce`.
291291

292+
Closures that don't use anything from their environment ("non capturing closures")
293+
can be coerced to function pointers (`fn`) with the matching signature.
294+
To adopt the example from the section above:
295+
296+
```rust
297+
let add = |x, y| x + y;
298+
299+
let mut x = add(5,7);
300+
301+
type Binop = fn(i32, i32) -> i32;
302+
let bo: Binop = add;
303+
x = bo(5,7);
304+
```
292305

293306
## Trait objects
294307

0 commit comments

Comments
 (0)