I have a two widgets in a simple GTK app:
extern crate gdk;
extern crate gtk;
use super::desktop_entry::DesktopEntry;
use gdk::enums::key;
use gtk::prelude::*;
pub fn launch_ui(_desktop_entries: Vec<DesktopEntry>) {
gtk::init().unwrap();
let builder = gtk::Builder::new_from_string(include_str!("interface.glade"));
let window: gtk::Window = builder.get_object("main_window").unwrap();
let search_entry: gtk::SearchEntry = builder.get_object("search_entry").unwrap();
let list_box: gtk::ListBox = builder.get_object("list_box").unwrap();
window.show_all();
search_entry.connect_search_changed(move |_se| {
let _a = list_box.get_selected_rows();
});
window.connect_key_press_event(move |_, key| {
match key.get_keyval() {
key::Down => {
list_box.unselect_all();
}
_ => {}
}
gtk::Inhibit(false)
});
gtk::main();
}
I need to change list_box
from both events. I have two closures that move
, but it is not possible to move list_box
to both closures simultaneously as I get the error:
error[E0382]: capture of moved value: `list_box`
What can I do?
A closure is Clone or Copy if it does not capture any values by unique immutable or mutable reference, and if all values it captures by copy or move are Clone or Copy , respectively.
Rust closures are harder for three main reasons: The first is that it is both statically and strongly typed, so we'll need to explicitly annotate these function types. Second, Lua functions are dynamically allocated ('boxed'.)
Moving closures Rust has a second type of closure, called a moving closure. Moving closures are indicated using the move keyword (e.g., move || x * x ). The difference between a moving closure and an ordinary closure is that a moving closure always takes ownership of all variables that it uses.
Rust's closures are anonymous functions you can save in a variable or pass as arguments to other functions. You can create the closure in one place and then call the closure elsewhere to evaluate it in a different context. Unlike functions, closures can capture values from the scope in which they're defined.
As explained in Shepmaster's answer, you can only move a value out of a variable once, and the compiler will prevent you from doing it a second time. I'll try to add a bit of specific context for this use case. Most of this is from my memory of having used GTK from C ages ago, and a few bits I just looked up in the gtk-rs documentation, so I'm sure I got some details wrong, but I think the general gist is accurate.
Let's first take a look at why you need to move the value into the closures in the first place. The methods you call on list_box
inside both closures take self
by reference, so you don't actually consume the list box in the closures. This means it would be perfectly valid to define the two closures without the move
specifiers – you only need read-only references to list_box
, you are allowed to have more than one read-only reference at once, and list_box
lives at least as long as the closures.
However, while you are allowed to define the two closures without moving list_box
into them, you can't pass the closures defined this way to gtk-rs: all functions connecting event handlers only accept "static" functions, e.g.
fn connect_search_changed<F: Fn(&Self) + 'static>(
&self,
f: F
) -> SignalHandlerId
The type F
of the handler has the trait bound Fn(&Self) + 'static
, which means that the closure either can't hold any references at all, or all references it holds must have static lifetime. If we don't move list_box
into the closure, the closure will hold a non-static reference to it. So we need to get rid of the reference before being able to use the function as an event handler.
Why does gtk-rs impose this limitation? The reason is that gtk-rs is a wrapper around a set of C libraries, and a pointer to the callback is eventually passed on to the underlying glib
library. Since C does not have any concept of lifetimes, the only way to do this safely is to require that there aren't any references that may become invalid.
We have now established that our closures can't hold any references. We still need to access list_box
from the closures, so what are our options? If you only have a single closure, using move
does the trick – by moving list_box
into the closure, the closure becomes its owner. However, we have seen that this doesn't work for more than one closure, because we can only move list_box
once. We need to find a way to have multiple owners for it, and the Rust standard library provides such a way: the reference-counting pointers Rc
and Arc
. The former is used for values that are only accessed from the current thread, while the latter is safe to move to other threads.
If I remember correctly, glib executes all event handlers in the main thread, and the trait bounds for the closure reflect this: the closure isn't required to be Send
or Sync
, so we should be able to make do with Rc
. Morevoer, we only need read access to list_box
in the closures, so we don't need RefCell
or Mutex
for interior mutability in this case. In summary, all you need is probably this:
use std::rc::Rc;
let list_box: gtk::ListBox = builder.get_object("list_box").unwrap();
let list_box_1 = Rc::new(list_box);
let list_box_2 = list_box_1.clone();
Now you have two "owned" pointers to the same list box, and these pointers can be moved into the two closures.
Disclaimer: I couldn't really test any of this, since your example code isn't self-contained.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With