Crates.io | closure_capture |
lib.rs | closure_capture |
version | 0.1.0 |
source | src |
created_at | 2024-06-24 10:17:05.622413 |
updated_at | 2024-06-24 10:17:05.622413 |
description | Capture variables are moved into closure or async block |
homepage | |
repository | https://github.com/xutianyi1999/closure-capture |
max_upload_size | |
id | 1282116 |
size | 6,292 |
Capture variables are moved into closure or async block
When using the move keyword, all external variables used in the closure will be moved into the closure.
Sometimes you may only need to move a few variables, and the rest of the variables will remain referenced.
At this time, you can use closure-capture to specify the variables to be captured.
link closure-capture
cargo.toml
[dependencies]
closure-capture = "0.1"
Move variables a and b into the closure
fn main() {
let a = 1;
let b = 2;
std::thread::spawn(closure_capture::closure!([a, b] () {
println!("{}", a + b)
}))
.join()
.unwrap();
}
Move variables a and b into the closure and modify a
fn main() {
let a = 1;
let b = 2;
std::thread::spawn(closure_capture::closure!([mut a, b] () {
a += b;
println!("{}", a)
}))
.join()
.unwrap();
}
With async block
#[tokio::main]
async fn main() {
let a = 1;
let b = 2;
tokio::spawn(closure_capture::async_block!([mut a, b] async {
a += b;
println!("{}", a)
}))
.await
.unwrap();
}