2017-09-04 41 views
2

我想增加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 `[[email protected]/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'](https://docs.rs/gtk/0.2.0/gtk/trait.ButtonExt.html#tymethod.connect_clicked)確實需要一個帶''static''生命週期的函數。相關(圍繞線程,但錯誤是一樣的):https://stackoverflow.com/a/28661524/1233251 –

回答

4

您無法將非靜態引用到GTK回調。您需要靜態或其他東西堆分配(例如在Box/RefCell/Rc /等)。

回調函數不是從連接到信號的範圍調用的,而是從主循環的稍後一點開始調用的。需要的是,無論你傳遞給閉包的東西是否仍然存在,那麼將會是任何東西'static,在main和主循環運行的位置之間堆棧分配或分配到棧上。最後一部分目前不能用Rust/GTK-rs很好地表達。

請參閱the example at the bottom in the gtk-rs docs for an example。它使用Rc<RefCell<_>>

+0

實施示例https://github.com/hfiguiere/gpsami/blob/f4e612dcaa35648d033846027e74903cdf62b7a4/src/mgapplication .RS#L96 – Infernion