-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclosure_out.rs
44 lines (36 loc) · 948 Bytes
/
closure_out.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
#![allow(unused)]
// Return closure as output
/*
move keyword must be used, which signals that all captures occur by value.
This is required because any captures by reference would be dropped as soon as the
function exited, leaving invalid references in the closure.
*/
fn create_fn() -> impl Fn() {
let text = "hello".to_string();
move || println!("fn {}", text)
}
fn create_fn_mut() -> impl FnMut() {
let text = "hello".to_string();
move || println!("fn mut {}", text)
}
fn create_fn_once() -> impl FnOnce() {
let text = "hello".to_string();
move || println!("fn once {}", text)
}
// TODO: dyn
// fn create_fn_once() -> dyn FnOnce() {
// let text = "hello".to_string();
// move || println!("fn once {}", text)
// }
fn main() {
let f = create_fn();
f();
f();
let mut f = create_fn_mut();
f();
f();
let f = create_fn_once();
f();
// Note: cannot call again
// f();
}