How to move a variable from closure?

I have a simple GTK application, and I need to select a folder and pass its variable paths outside of closing.

let mut path = "".to_owned();

button_open.connect_clicked(move |_| {
    let file_chooser = gtk::FileChooserDialog::new(
        "Open File", None, gtk::FileChooserAction::SelectFolder,
        [("Open", gtk::ResponseType::Ok), ("Cancel", gtk::ResponseType::Cancel)]);
    if file_chooser.run() == gtk::ResponseType::Ok as i32 {
        let filename = file_chooser.get_current_folder().unwrap();
    }

    file_chooser.destroy();
});

How to assign filenameto path? If I just write

path = filename;

I get this error:

src\main.rs:46:13: 46:28 error: cannot assign to captured outer variable in an `Fn` closure
src\main.rs:46             path = filename;
+4
source share
1 answer

You cannot do this for several reasons. Here is the definition of the method connect_clicked():

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

, , Fn 'static. , -, ( FnMut), - ( , 'static). , path, .

, gtk-rs , GTK , Send , , 'static bound, , FnMut. , -, .

, Rc<RefCell<..>> :

let path: Rc<RefCell<Option<String>>> = Rc::new(RefCell::new(None));
let captured_path = path.clone();  // clone the Arc to use in closure
...
// inside the closure
*captured_path.borrow_mut() = Some(filename);

Arc<Mutex<..>>, , , gtk-rs GTK , .

+7

Source: https://habr.com/ru/post/1622898/


All Articles