Help on self-referential struct

struct OuterStruct {
    data_vec:  Vec<u8>,
    // inner struct as mut ref to the data_vec
    data_accessor: InnerStruct<'a>,
}

pub struct InnerStruct<'a> {
    // mut reference to the data
    data: &'a mut [u8],
    // other fields
    ....
}

How can I represent this relationship in rust?
Will ouroboros help ?

You can't do this with purely safe rust code, you'll need either unsafe or a library that wraps it for you. ouroboros is an example of such library, along with yokable and self_cell to name a few other popular ones.

Sure, not a problem:

use ouroboros::self_referencing;

#[self_referencing]
struct OuterStruct {
    data_vec:  Vec<u8>,
    // inner struct as mut ref to the data_vec
    #[borrows(mut data_vec)]
    #[covariant]
    data_accessor: InnerStruct<'this>,
}

pub struct InnerStruct<'a> {
    // mut reference to the data
    data: &'a mut [u8],
    // other fields
    // ....
}

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.