Reference to a field from another field

Hello, I try to make a struct which have two fields. One is a vec of u8 and the other is a vec of &u8, where the &u8 refer to the first u8. (In reality I don't use u8, but it's simplify my example)

struct Foo<'a> {
    bar: Vec<u8>,
    baz: Vec<&'a u8>
}

The declaration work perfectly but I don't know how to build such of struct even with unsafe code...
I think it can theoretically work because bar will never be change, it is "immutable", in the rest of my program.
Do you have any solution ?

1 Like

This is called a self-referential struct, and is impossible in safe code. Consider changing the type of bar to &'a [u8] so that Foo doesn't actually own the memory in bar.

3 Likes

Or use baz: Vec<usize> with indices into bar.

1 Like

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.