-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathmove.rs
36 lines (29 loc) · 865 Bytes
/
move.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
#![allow(unused)]
fn main() {
// Closures can capture variables by
// - Borrow immutable reference &T
// - Borrow mutable reference &mut T
// - Take ownership of value T
// Borrow immutable reference
let s = "hello".to_string();
let f = || println!("borrow: {}", s);
f();
println!("main: {}", s);
// Borrow mutable
let mut s = "hello".to_string();
let mut f = || s += " world";
f();
println!("main: mut {}", s);
// Taking ownership
// Using `move` forces closure to take ownership of captured variables
let s = "hello".to_string();
let f = move || {
println!("move: {}", s);
// Force drop on s
std::mem::drop(s);
};
// Cannot call twice - ownership moved into f
f();
// Cannot call print - ownership moved into f
// println!("main {}", s);
}