Easier "local" code inside closures

Hi!
Am I the only one that thinks this kind of code is a pain?:

let a = Rc::new("proc macro sucks");
let b = Rc::new(42);

// The bottom code is looooonng
let my_closure = {
  let a = a.clone();
  let b = b.clone();
  move || { println!("{} {}", a, b) }
}

drop((a,b));
drop(my_closure);

Maybe this is a niche problem, maybe not, but it would be really nice to write something like:

let my_closure = move || { println!("{} {}", local { a.clone() }, local { b.clone() }) }

(not only for clone of course)

Any thoughts?

You can use the following, with a simple macro:

macro_rules! clone {
    ( $( $x:ident ),+ => $body:expr ) => {{
        $( let $x = $x.clone(); )+
        move || $body
    }}
}

fn main() {
    use std::rc::Rc;

    let a = Rc::new("proc macro sucks");
    let b = Rc::new(42);

    let my_closure = clone!(a, b => {
        println!("{} {}", a, b)
    });

    my_closure();
}

If you use nightly, then this RFC may interest you. It seems to be what you are looking for (with a different syntax).

1 Like

This seems to be a good solution.
There is still the problem when there is a lot of variables that need different operations each other (not necessarily clone), but this kind of situation happens less often.

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.