类型必须满足静态生命周期

6

我正在尝试增加一个Rust和GTK-RS应用程序的结构,但是我无法弄清如何处理事件连接。我发现问题在于错误的生命周期,但我并不真正理解它如何被修复。

#[derive(Debug)]
struct CreatingProfileUI {
    window: gtk::MessageDialog,
    profile_name_entry: gtk::Entry,
    add_btn: gtk::Button,
    cancel_btn: gtk::Button,
}

#[derive(Debug)]
struct UI {
    window: gtk::Window,

    // Header
    url_entry: gtk::Entry,
    open_btn: gtk::Button,

    // Body
    add_profile_btn: gtk::Button,
    remove_profile_btn: gtk::Button,
    profiles_textview: gtk::TextView,

    // Creating profile
    creating_profile: CreatingProfileUI,

    // Statusbar
    statusbar: gtk::Statusbar,
}

impl UI {
    fn init(&self) {
        self.add_profile_btn
            .connect_clicked(move |_| { &self.creating_profile.window.run(); });
    }
}

我遇到了以下错误:

error[E0477]: the type `[closure@src/main.rs:109:46: 111:6 self:&UI]` does not fulfill the required lifetime
   --> src/main.rs:109:30
    |
109 |         self.add_profile_btn.connect_clicked(move |_| {
    |                              ^^^^^^^^^^^^^^^
    |
    = note: type must satisfy the static lifetime

1
ButtonExt::connect_clicked 要求一个具有 'static 生命周期的函数。相关内容(关于线程,但错误类似):https://dev59.com/lV4b5IYBdhLWcg3wzUja#28661524 - E net4
1个回答

8
您不能将非静态引用移入GTK回调函数中。您需要使用一些静态的东西或堆分配的东西(例如在Box/RefCell/Rc/等中)。
回调函数不是从连接到信号的作用域调用的,而是在稍后从主循环点调用的。需要确保您传递给闭包的任何内容在那时仍然存在,这可以是任何'static、堆分配的或者在主循环运行之间的栈上分配的东西。目前,最后一部分在Rust/GTK-rs中无法清晰地表达。
请参见gtk-rs文档底部的示例。它使用了一个Rc<RefCell<_>>

1
一个实现的例子 https://github.com/hfiguiere/gpsami/blob/f4e612dcaa35648d033846027e74903cdf62b7a4/src/mgapplication.rs#L96 - skhalymon

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接