One variable, two closures


#1

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


#2

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.


#3

Can i use this for other types as well ?


#4

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.


#5

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