Hey all!
Here's a very basic sketch of what I'm trying to do, I have lists of values (or only one in this basic example) which I want to reference from another place in the same struct. I need to do all that inside the methods of the struct. I can easily do that by saving indices, but I'm wondering if there's a way to accomplish it using references as well?
The following example does not compile:
struct Total<'a> {
subs: Vec<SubStruct<'a>>,
sub_refs: Vec<&'a SubStruct<'a>>
}
struct SubStruct<'a> {
val: &'a Dummy
}
struct Dummy {
//stuff
}
fn main() {
println!("Hello, world!");
let mut total = Total {
subs: vec!(SubStruct {val:&Dummy{}}, SubStruct{val:&Dummy{}}),
sub_refs: vec!(),
};
total.test();
}
impl<'a> Total<'a> {
pub fn test(&mut self, index: usize) {
self.sub_refs.push(&self.subs[index]);
}
}
I think I understand the problem here, I can't gurantee the values in the subs Vector will live as long as the whole struct, something else might clear the Vector or something similar. If that's the case, is there some way around it, like a push only Vector?
And if that's not the problem, I'd be glad to learn the problem.