closure_capture 0.1.0

Capture variables are moved into closure or async block
Documentation
  • Coverage
  • 33.33%
    1 out of 3 items documented1 out of 1 items with examples
  • Size
  • Source code size: 5.96 kB This is the summed size of all the files inside the crates.io package for this release.
  • Documentation size: 1.13 MB This is the summed size of all files generated by rustdoc for all configured targets
  • Links
  • xutianyi1999/closure-capture
    0 0 0
  • crates.io
  • Dependencies
  • Versions
  • Owners
  • xutianyi1999

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();
}