capypad
0 day streak
rust / intermediate
Snippet

Capturing Environment with 'move' Closures

The 'move' keyword forces a closure to take ownership of the variables it captures from the environment, rather than just borrowing them. This is often required when passing closures to new threads.

snippet.rs
rust
1
2
3
4
5
6
7
8
9
10
11
fn main() {
let data = vec![1, 2, 3];
let closure = move |x: i32| {
println!("Data from environment: {:?}", data);
data.contains(&x)
};
 
println!("Result: {}", closure(2));
// println!("{:?}", data); // Error: value moved
}
Breakdown
1
move |x: i32|
Indicates that the closure takes ownership of captured variables.
2
data.contains(&x)
The closure uses the captured 'data' vector which has been moved into its scope.