如何从回调闭包中使用按钮本身?
How to use the button itself from the callback closure?
我已经从 gtk-rs 示例中编写了这段小代码,但是它无法编译,因为不能从闭包中使用按钮。
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();
}
编译器写道:
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 |_| {
^~~~~~
如何解决这个问题?
我不能通过引用传递变量:它是无效的,因为闭包的生命周期可能超过 main 的生命周期,编译器说。
注:我用这个Cargo.toml
编译:
[package]
name = "test"
version = "0.1.0"
authors = ["Me"]
[features]
default = ["gtk/v3_16"]
[dependencies]
gtk = { git = "https://github.com/gtk-rs/gtk.git" }
下划线不代表"same name as outside the closure",它代表"make the closure argument unused/unusable"。尝试命名参数:
button.connect_clicked(move |button| {
button.hide();
});
我已经从 gtk-rs 示例中编写了这段小代码,但是它无法编译,因为不能从闭包中使用按钮。
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();
}
编译器写道:
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 |_| { ^~~~~~
如何解决这个问题?
我不能通过引用传递变量:它是无效的,因为闭包的生命周期可能超过 main 的生命周期,编译器说。
注:我用这个Cargo.toml
编译:
[package]
name = "test"
version = "0.1.0"
authors = ["Me"]
[features]
default = ["gtk/v3_16"]
[dependencies]
gtk = { git = "https://github.com/gtk-rs/gtk.git" }
下划线不代表"same name as outside the closure",它代表"make the closure argument unused/unusable"。尝试命名参数:
button.connect_clicked(move |button| {
button.hide();
});