如何从单击按钮的条目中获取信息?

How do I get information from an entry on button click?

我想从单击按钮时的条目获取输入,并在单击另一个按钮时显示该信息。这给了我一个错误,因为闭包取得了我的 firstname 变量的所有权,我想在其中存储信息。

如何从条目中获取信息并重新使用它?

// import gtk libs
extern crate gio;
extern crate gtk;

// declare use of gtk
use gtk::prelude::*;

fn main() {
    let mut firstname = String::new();

    if gtk::init().is_err() {
        println!("Failed to initialize GTK.");
        return;
    }
    let glade_src = include_str!("builder.glade");
    let builder = gtk::Builder::new_from_string(glade_src);

    let window: gtk::Window = builder.get_object("window1").unwrap();
    let buttonSubmit: gtk::Button = builder.get_object("buttonSubmit").unwrap();
    let buttonShow: gtk::Button = builder.get_object("buttonShow").unwrap();
    let entryFirstname: gtk::Entry = builder.get_object("entryFirstname").unwrap();

    // get information from entry
    buttonSubmit.connect_clicked(move |_| {
        firstname = entryFirstname.get_buffer().get_text();
    });

    // output information
    let firstname_clone = firstname.clone();
    buttonShow.connect_clicked(move |_| {
        println!("Firstname: {}", firstname_clone);
    });

    window.show_all();

    gtk::main();
}

一旦你的字符串被移动到闭包中,编译器就不能再静态地检查你没有混合对它的读写访问。您需要使用 RefCell to enable runtime selection of read/write accesses, probably combined with Rc 进行适当的内存管理:

let firstname = Rc::new(RefCell::new(String::new()));
let firstname_clone = firstname.clone();
// ...
buttonSubmit.connect_clicked(move |_| {
    firstname.replace(entryFirstname.get_buffer().get_text());
});
// ...
buttonShow.connect_clicked(move |_| {
    println!("Firstname: {}", firstname_clone.borrow());
});