capypad
0 day streak
rust / intermediate
Snippet

Closures: Capturing Environment Variables

Closures can capture variables from their surrounding environment. Rust determines the capture mode automatically based on how the closure uses the variable: by reference, by mutable reference, or by value. The move keyword forces a closure to take ownership of captured variables, which is essential when passing closures to threads or when you need guaranteed ownership.

snippet.rs
rust
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
fn main() {
let x = 4;
let equal_to_x = |z| z == x;
println!("Equal to 4: {}", equal_to_x(4));
let y = 4;
let owns_y = move || {
println!("y taken: {}", y);
};
let v = vec![1, 2, 3];
let uses_v = || println!("v.len(): {}", v.len());
uses_v();
drop(v);
}
Breakdown
1
let equal_to_x = |z| z == x;
Closure captures x by reference since it only reads x
2
let owns_y = move || { ... }
move forces ownership transfer; closure now owns y and can use it even after y goes out of scope elsewhere
3
let uses_v = || println!("v.len(): {}", v.len())
Captures v by reference since only reading; v can still be dropped after this closure is used