Coming from JavaScript, I'm learning Rust, and I keep running into the same issue.
Let's say that I'm building a native window wrapper. Something like this:
struct MyWindowWrapper {
native_window: …; // Native window type
}
impl MyWindowWrapper {
fn new() {
let native_window = …; // Some platform specific code.
MyWindowWrapper {
native_window: native_window
}
}
fn update_title(&self, title: String) {
self.native_window.set_title(title);
}
}
Now, this works. Now I also want MyWindowWrapper
to handle events from the native window (let's say, on_window_clicked
). So I add a method to MyWindowWrapper
and want native_window
to call it. So native_window need a reference to the new instance of MyWindowWrapper
:
impl MyWindowWrapper {
fn new() {
let native_window = …; // Some platform specific code.
let wrapper = MyWindowWrapper {
native_window: native_window
};
native_window.set_handler(&wrapper);
wrapper
}
fn update_title(&self, title: String) {
self.native_window.set_title(title);
}
fn on_window_clicked(&self) {
// will be called by native_window.
}
}
But in the implementation of set_handler
, I can't keep the reference to the wrapper. Rust bails with expected lifetime parameter
when I try to use a struct that holds a reference to MyWindowWrapper
.
Maybe I need a lifetime indeed. I was also wondering if I should be using Rc<MyWindowWrapper>
.
Edit: just tried with a lifetime, and it works. But I'm wondering if it's the right way to do it.
But I want to do understand what is the "Rust" way to do such a thing.
Any feedback would be appreciated. Thank you.