Standard way to name clones for move capture?

In this sort of situation...

let x = Arc::new(foo);
let x_1 = x.clone();
tokio::spawn(async move {
    // something involving `x_1`
});
bar(x).await;

I often have a litany of such clones and I have taken to calling them x_1, x_2, etc. depending on how many closures whose appetite for clones I need to satisfy.

At the risk of inviting a bikeshedding, are there good general techniques for avoiding this cruft, and if not, is there a convention for naming and using these extra identifiers?

2 Likes

You can use inner scopes to limit the extent of the clone bindings:

let x = Arc::new(foo);
tokio::spawn({
    let x=x.clone();
    async move {
        // something involving `x`
    }
});
bar(x).await;
4 Likes

If there's already a convenient scope, I just shadow it. Otherwise I use integers, i.e. x1, x2 or if I only need one extra name, x_clone.

Thank you both! I like the extra scope idea - I haven't seen that before.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.