#macro #capture #struct

captur

Macro to capture whole structs from disjoint fields in a closure

1 unstable release

0.1.0 Jul 1, 2021

#16 in #capture

Download history 49/week @ 2022-08-18 103/week @ 2022-08-25 78/week @ 2022-09-01 147/week @ 2022-09-08 22/week @ 2022-09-15 64/week @ 2022-09-22 76/week @ 2022-09-29 77/week @ 2022-10-06 321/week @ 2022-10-13 77/week @ 2022-10-20 87/week @ 2022-10-27 68/week @ 2022-11-03 98/week @ 2022-11-10 60/week @ 2022-11-17 54/week @ 2022-11-24 23/week @ 2022-12-01

251 downloads per month
Used in 2 crates (via girt-core)

ISC license

6KB
98 lines

Crates.io docs GitHub license

Captur

Starting in Rust 2021, Rust will no longer capture whole structs and instead will only capture a disjoint set of the fields used in a closure. In some cases, it is necessary to capture the structs to retain a particular drop order. This macro will capture the struct within the closure, ensuring the correct drop order.

The Fix

The typical fix to this problem is to create an unused reference to the struct.

let some_struct = SomeStruct::new();
let result = || {
    // capture some_struct within the closure
    let _ = &some_struct;
    println!("{}", some_struct.y);
}

While this is trivial to implement in closures where capturing is required, without a comment it, the meaning of the unused line is difficult to determine. This macro provides a self documenting and potentially more concise way to capture the structs.

Installation and Usage

[dependencies]
captur = "0.1"
use captur::capture;

fn send_event_and_action(action: &Action, event: Event) {
    send(|sender| {
        capture!(action, event);
        sender.send(action.name.as_str(), event.code);
    });
}

License

Captur is released under the ISC license. See LICENSE.

No runtime deps