@@ -5,13 +5,11 @@ output parameters should also be possible. However, anonymous
5
5
closure types are, by definition, unknown, so we have to use
6
6
` impl Trait ` to return them.
7
7
8
- The valid traits for returns are slightly different than before :
8
+ The valid traits for returning a closure are :
9
9
10
- * ` Fn ` : normal
11
- * ` FnMut ` : normal
12
- * ` FnOnce ` : There are some unusual things at play here, so the [ ` FnBox ` ] [ fnbox ]
13
- type is currently needed, and is unstable. This is expected to change in
14
- the future.
10
+ * ` Fn `
11
+ * ` FnMut `
12
+ * ` FnOnce `
15
13
16
14
Beyond this, the ` move ` keyword must be used, which signals that all captures
17
15
occur by value. This is required because any captures by reference would be
@@ -31,12 +29,20 @@ fn create_fnmut() -> impl FnMut() {
31
29
move || println!("This is a: {}", text)
32
30
}
33
31
32
+ fn create_fnonce() -> impl FnOnce() {
33
+ let text = "FnOnce".to_owned();
34
+
35
+ move || println!("This is a: {}", text)
36
+ }
37
+
34
38
fn main() {
35
39
let fn_plain = create_fn();
36
40
let mut fn_mut = create_fnmut();
41
+ let fn_once = create_fnonce();
37
42
38
43
fn_plain();
39
44
fn_mut();
45
+ fn_once();
40
46
}
41
47
```
42
48
@@ -46,6 +52,5 @@ fn main() {
46
52
47
53
[ fn ] : https://doc.rust-lang.org/std/ops/trait.Fn.html
48
54
[ fnmut ] : https://doc.rust-lang.org/std/ops/trait.FnMut.html
49
- [ fnbox ] : https://doc.rust-lang.org/std/boxed/trait.FnBox.html
50
55
[ generics ] : ../../generics.md
51
56
[ impltrait ] : ../../trait/impl_trait.md
0 commit comments