Created
April 27, 2018 02:52
-
-
Save rust-play/b3dbceed75644265df9f2bc2c2b06077 to your computer and use it in GitHub Desktop.
Code shared from the Rust Playground
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
struct AppData<'a> { | |
name: &'a str | |
} | |
impl<'a> AppData<'a> { | |
pub fn go_to_screen(&self, screen: &str) { | |
println!("app {} is going to screen {}", self.name, screen); | |
} | |
} | |
// mimicking Gtk; F: Fn() + 'static | |
fn button_connect_clicked<F: Fn()+'static>(closure: F) { | |
closure(); | |
} | |
fn main() { | |
// In my real app, AppData contains connection to database. | |
// So cannot be cloned. | |
let app_data:AppData = AppData{name:"demo_app"}; | |
let app_data_ref = &app_data; | |
let closure_a = || { | |
app_data_ref.go_to_screen("screen1"); | |
}; | |
//gtk::init(); | |
//initialize window etc.. | |
button_connect_clicked(closure_a); | |
//gtk::main(); | |
} | |
/* | |
Here the error is that closure_a appears to live beyond main, but app_data_ref | |
cease to exist after main(). | |
Actually, we never exit the main() because call to gtk::main() blocks until app exits. | |
So, app_data_ref is valid as long as closure_a is valid. | |
What's a polite way to tell the compiler that it's wrong in this case? | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment