-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathclosure_move.rs
42 lines (31 loc) · 1.02 KB
/
closure_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
37
38
39
40
41
42
use std::thread;
fn main() {
// Move
// 3 ways values are captured from their environment
// - borrowing immutable
// - borrowing mutable
// - taking ownership
// borrow immutable
let list = vec![1, 2, 3];
println!("Before defining closure: {list:?}");
let f_borrow_immut = || println!("From closure: {list:?}");
println!("Before calling closure: {list:?}");
f_borrow_immut();
println!("After calling closure: {list:?}");
// borrowing mutable
println!("--- mutable borrow ---");
let mut list = vec![1, 2, 3];
println!("Before defining closure: {list:?}");
// Captures mutable ref
let mut borrows_mutably = || list.push(7);
borrows_mutably();
println!("After calling closure: {list:?}");
// taking ownership
// move is useful for thread
println!("--- move ---");
let list = vec![1, 2, 3];
println!("Before defining closure: {list:?}");
thread::spawn(move || println!("From thread: {list:?}"))
.join()
.unwrap();
}