How to creat self referential struct

struct My<'a> {
    x: Vec<u32>,
    z: &'a [u32],
}

fn main() {
    let ok = My {
        x: vec![1, 2, 3, 4],
        z: &x,
    };
}

It is not possible to create self-referential types in safe Rust for pretty obvious technical reasons (they would trivially lead to dangling references when moved). The good news is: you don't need them! Tell us what your high-level goal is – likely, the solution will be to refactor your data model and split it up into an owning and a "view" part.

3 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.