Helper macro for cloning into a closure

When writing event-driven code using callbacks (e.g. for Wayland), I often have code that has to clone reference counted objects with interior mutability into closures. I end up with code like the following.

let thing_c = thing.clone();
let other_thing_c = other_thing.clone();
fn_taking_cb(move || {
    // use `other_thing_c`
    let thing_c2 = thing_c.clone();
    another_cb_fn(move || {
        // use `thing_c2`
    });
    // use `thing_c`.
});
// use `thing`, `other_thing`.

which gets verbose (plus you have to think of names for all the clones).

A way of getting round the naming issue is using blocks:

fn_taking_cb({
    let thing = thing.clone();
    let other_thing = other_thing.clone();
    move || {
        // use `other_thing`
        another_cb_fn({
            let thing = thing.clone();
            move || {
                // use `thing`
            }
        });
        // use `thing`.
    }
});
// use `thing`, `other_thing`

but this requires an extra level of nesting of blocks.

I saw a neat solution to this problem in the gtk-rs bindings. They have a macro that does this cloning for you, so you end up with code like:

fn_taking_cb(clone_for_closure!(thing, other_thing, move || {
    // use `other_thing`.
    another_cb_fn(clone_for_closure!(thing, move || {
        // use `thing`.
    }));
    // use `thing`.
}));
// use `thing`, `other_thing`.

I wonder if this pattern is ubiquitous enough to warrant some support in the standard library (with bikeshedded name)?

EDIT Oh I found an open RFC issue for this: Officially implement a clone macro · Issue #2022 · rust-lang/rfcs · GitHub.

2 Likes

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.