Is it okay to use lifetimes like that?

Let's suppose that I have an object of type "native_subsystem", it produces another object closely linked to it, let's call it "native_window".
The point is, native_window needs that native_subsystem is alive to function properly but that relationship is not clear for the Rust language. Would it be okay to create a "struct holder <'s> (sub: &' s native_subsystem, win: native_window)" to ensure that "native_ window" does not live longer than "native_subsystem"? Is there a better way to do this?

1 Like

Sure, you can do that.

1 Like

If a native window is associated with a specific native subsystem, it might be clearer to include a reference to the subsystem struct in your window struct directly, rather than splitting it off into a separate struct. It's a style and legibility decision, though - both ways are valid, and either one might be appropriate depending on circumstance.

#[derive(Debug)]
struct NativeSubsystem;

impl NativeSubsystem {
  fn window(&self) -> NativeWindow {
    NativeWindow {
      subsystem: &self,
      // ...
    }
  }
}

#[derive(Debug)]
struct NativeWindow<'a> {
    subsystem: &'a NativeSubsystem,
    // ...
}

fn main() {
    let subsystem = NativeSubsystem;
    let window = subsystem.window();
    println!("{:?}", window);   
}

There is one significant semantic difference between the two approaches: with your holder struct, the caller can decompose a holder into a reference to a native subsystem and an owned native window, then drop the reference to the subsystem without dropping the window, allowing the two to be separated and allowing the subsystem to be dropped before the window. "Don't do that" is a valid restriction, but it's not one the compiler can easily enforce. If the reference is part of the window structure, that's not possible.

2 Likes

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.