Making a container containing an object and a reference to it

Here's an example of what I'm talking about:

struct Inner {}

struct Outer<'a> {
  pub r: &'a Inner
}

impl<'a> Container<'a> {
  fn new() -> Self {
    let obj = Inner {};
    let obj2 = Outer { r: &obj };
    Self { a: obj, b: obj2 }
// cannot move out of `obj` because it is borrowed
  }
}

How can I achieve the desired result?

For my usecase Inner is a winit Window, Outer is a wgpu context and Container is a wrapper for drawing images to the window.

Search for “self-referencing struct” for many prior results.

TL;DR, Rust doesn’t support this, the most convenient approach is to just avoid the desire to pack these things into a single struct, as long as that’s possible; otherwise, there are a few macro-based crates that allow you do it without needing to touch unsafe or raw pointers yourself. A simple such crate is self_cell - Rust

On the point of avoiding the issue:

I’m not a user of those window-related crates, but it seems like maybe using the Window as an owned value and/or shared via Arc<Window> might work just as well?

Yes, if you pass a (cloned) Arc<Window> you can get back a Surface<'static>, so borrow checking is no longer a consideration.

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.