Struct that owns an object that needs a reference to the struct

I have a question to do with reference. Imagine we have:

pub struct B<'b>{
a_ref:&'b A
}
impl<'b> B<'b>{
pub fn new(&self){}

}

pub struct A<'a> {
b: B<'a>
}
impl A<'a>{

pub fn new()->Self{
 Self{..?}
}

How would you program something like this? Or, more generally, how do I separate some functionality of a struct into sub structs but operate on the common data of the parent struct (without passing references into every function)?

Self-referential structs aren't possible in safe Rust, because they don't make sense (or at the very least not useful). If a value is moved, then all references to it would be invalidated, including the ones inside itself.

They are also usually a code smell, an indication of a design error, and in the overwhelming majority of the cases, you don't really need a self-referential type. What are you trying to achieve at a higher level?

2 Likes

Yeah, I don't want it to be self-referential! I want a single struct to own all the data, but have the functionality be handled by different 'sub-structs'. Any alternative, more idiomatic design you can recommend would be splendid!

In this case, you would create one owning type without any lifetimes, and multiple non-owning types with a lifetime, used by a reference to the original, underlying, owned data. For example:

struct Owner {
    buffer: Vec<u8>,
}

impl Owner {
    fn view_one(&self) -> ViewOne<'_> {
        ViewOne { buffer: &self.buffer }
    }

    fn view_two(&self) -> ViewTwo<'_> {
        ViewTwo { buffer: &self.buffer }
    }
}

struct ViewOne<'a> {
    buffer: &'a [u8],
}

struct ViewTwo<'a> {
    buffer: &'a [u8],
}
7 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.