error[E0507]: cannot move a captured variable in an `Fn` closure

After creating a gtk::Image, I’m trying to access it in a couple of closures, but getting error messages. I assume I need something like RefCell<>, but can’t get the invocation right:

error[E0507]: cannot move out of `image_widget`, a captured variable in an `Fn` closure
  --> src/main.rs:46:43
   |
32 |       let image_widget: Image = builder.object("image_widget").expect("Couldn't get image_widget");
   |           ------------ captured outer variable
...
37 |       action_open.connect_activate(clone!(@weak window => move |_, _| {
   |  __________________________________-
38 | |         let file_chooser = FileChooserDialog::new(
39 | |             Some("Open image"),
40 | |             Some(&window),
...  |
46 | |             file_chooser.connect_response(move |file_chooser, response| {
   | |                                           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ move out of `image_widget` occurs here
...  |
51 | |                     image_widget.set_from_file(Some(filename));
   | |                     ------------
   | |                     |
   | |                     variable moved due to use in closure
   | |                     move occurs because `image_widget` has type `gtk4::Image`, which does not implement the `Copy` trait
...  |
65 | |         file_chooser.show();
66 | |     }));
   | |______- captured by this `Fn` closure

For more information about this error, try `rustc --explain E0507`.

I’d be grateful for any suggestions.

You need to clone image_widget as otherwise you can’t have it moved into the closure and still be able to use it outside the closure. Cloning widgets just increases the reference count, all clones will still refer to the very same widget.

Thanks, yes. I needed

button.connect_clicked(clone!(@weak window => move |_| {}));

and

file_chooser.connect_response(clone!(@weak image => move |file_chooser, response| {}));

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.