#struct-fields #capture #struct #macro #disjoint-set

captur

Macro to capture whole structs from disjoint fields in a closure

3 releases (stable)

1.0.1 Jul 21, 2024
1.0.0 Jun 30, 2024
0.1.0 Jul 1, 2021

#502 in Rust patterns

Download history 129/week @ 2024-07-14 199/week @ 2024-07-21 88/week @ 2024-07-28 29/week @ 2024-08-04 63/week @ 2024-08-11 20/week @ 2024-08-18 24/week @ 2024-08-25 42/week @ 2024-09-01 38/week @ 2024-09-08 52/week @ 2024-09-15 57/week @ 2024-09-22 65/week @ 2024-09-29 23/week @ 2024-10-06 35/week @ 2024-10-13 23/week @ 2024-10-20 9/week @ 2024-10-27

92 downloads per month
Used in 4 crates

ISC license

11KB

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, 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 = "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);
    });
}

Supported Rust Versions

This project will support Rust versions since 1.56.0, the first release of Rust 2021.

Dropping support for a Rust version will result in a major version bump, following Semantic Versioning.

License

Captur is released under the ISC license. See LICENSE.

No runtime deps