One variable, two closures

Here's a snippet for what i've got:

fn main() {
conifg_background.connect_activate(|_|{
    /*  . . . . . */
    but_save.connect_clicked(move |_|{
			let (r,g,b) = (r_slider.get_value(),g_slider.get_value(),b_slider.get_value());
			println!("Saved: (R,G,B) = ({},{},{})",r,g,b);
		});
              /* . . . . . */  
});

Basically what i want is to have an (r,g,b) in my main function which i can use and change in other closures.

Here are what the gtk docs say:

fn connect_clicked<F: Fn(&Self) + 'static>(&self, f: F) -> u64
fn connect_activate<F: Fn(&Self) + 'static>(&self, f: F) -> u64

This will require a Arc<Cell<(U32,U32,U32)>> since you can't actually share mutable references with these closures. Cell should be fine since that tuple will be copyable.

1 Like

Can i use this for other types as well ?

Oh yes - it's the standard way to get around the problem. If the types aren't Copy then use a RefCell instead of Cell.

1 Like

A small correction: Arc will always work, but if you don't have multiple threads Rc is more appropriate and faster.

1 Like