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