Lifetime & Borrowing inside a struct method

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.

It is generally not possible in Rust to have one field store a reference to another field in the same struct. The alternatives are:

  1. Use indexes to refer into the other vector. (or keys for a map)
  2. Just clone the value and have several duplicates of it.
  3. Use a smart pointer like Rc that is designed for sharing a value.

An Rc is a special container that provides immutable access to a shared value. When you clone a Rc, that gives a new handle to the same underlying value, so cloning an Rc is very cheap. If you want to modify it, you can wrap it in an RefCell as well, since a RefCell allows mutation through immutable references.

Rc seems like an exact fit for what I need, thank you!