How can I create a reference on another member in a struct

Hi, guys. I have a struct Dummy, and a is a vector, b is a reference of some data in a, i.e. &[T]. which b have the same lifetime as a.

struct Dummy<T> {
    a: Vec<T>,
    b: &'x [T], // The lifetime specifier `x` have the same lifetime as member `a`

It this even possible?

My real-world use case:
I have a vector Vec<T> which is pretty large, and I will do some calculation to get a sub-range(usually less than 100 elements) from the Vec<T>(as a reference), so I don't have to clone the sub vector, which will incur some memory allocation.

This is known as a self-referential type, and it cannot be implemented in safe Rust. If you can tell us more about your use case, someone may be able to suggest an alternative strategy.

1 Like

For this, I’d probably just store the Range<usize> and index into the vector each time. It’ll be almost as efficient as accessing through a slice pointer, and won’t run into trouble if the vector needs to reallocate its buffer for whatever reason.


Good, I found another way by implementing a method to returning a reference &[T] of the Vec<T> to the end user.

So I don't have to bookkeep the sub-range in the struct.

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.