Reputation: 42909
I have written this little code from gtk-rs examples, but it cannot compile since the button cannot be used from the closure.
extern crate gtk;
use gtk::prelude::*;
fn main() {
if gtk::init().is_err() {
println!("Failed to initialize GTK.");
return;
}
let window = gtk::Window::new(gtk::WindowType::Toplevel);
let button = gtk::Button::new_from_stock("Click me !");
window.add(&button);
window.connect_delete_event(|_, _| {
gtk::main_quit();
Inhibit(false)
});
button.connect_clicked(move |_| {
button.hide(); // error
});
window.show_all();
gtk::main();
}
The compiler writes:
src/main.rs:22:3: 22:9 error: cannot move `button` into closure because it is borrowed [E0504] src/main.rs:22 button.hide(); ^~~~~~ src/main.rs:21:2: 21:8 note: borrow of `button` occurs here src/main.rs:21 button.connect_clicked(move |_| { ^~~~~~
How to solve this problem?
I cannot pass variables by reference: it is invalid because the lifetime of closure may exceed the lifetime of main, compiler says.
Note: I use this Cargo.toml
to compile:
[package]
name = "test"
version = "0.1.0"
authors = ["Me"]
[features]
default = ["gtk/v3_16"]
[dependencies]
gtk = { git = "https://github.com/gtk-rs/gtk.git" }
Upvotes: 2
Views: 359
Reputation: 14617
underscore doesn't mean "same name as outside the closure", it means "make the closure argument unused/unusable". Try naming the argument:
button.connect_clicked(move |button| {
button.hide();
});
Upvotes: 3