closure_capture

Crates.ioclosure_capture
lib.rsclosure_capture
version0.1.0
sourcesrc
created_at2024-06-24 10:17:05.622413
updated_at2024-06-24 10:17:05.622413
descriptionCapture variables are moved into closure or async block
homepage
repositoryhttps://github.com/xutianyi1999/closure-capture
max_upload_size
id1282116
size6,292
XTY (xutianyi1999)

documentation

README

closure-capture

Capture variables are moved into closure or async block

Latest version Documentation License

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.

Usage

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();
}
Commit count: 8

cargo fmt