How to create a reference var in struct?

In the code below I want to have a reference of first_pos_tuple_vec or second_pos_tuple_vec assignable to selected_pos_tuple_vec; how to do that? (tried to apply lifetimes as error help suggested, but got the error below)

pub struct X<'a> {
    pub first_pos_tuple_vec: Vec<(f64, f64)>,
    pub second_pos_tuple_vec: Vec<(f64, f64)>,
    pub selected_pos_tuple_vec: &'a Vec<(f64, f64)>,
}

impl <'a> X<'a> {
    pub fn new() -> X<'a> {
        X {
            first_pos_tuple_vec: Vec::new(),
            second_pos_tuple_vec: Vec::new(),
            selected_pos_tuple_vec: &Vec::new(),
        }
    }
    pub fn test_selected(&mut self) {
        self.first_pos_tuple_vec.push((1.0, 2.0));
        self.first_pos_tuple_vec.push((3.0, 4.0));
        self.first_pos_tuple_vec.push((5.0, 6.0));

        self.second_pos_tuple_vec.push((7.0, 8.0));
        self.second_pos_tuple_vec.push((9.0, 10.0));
        self.second_pos_tuple_vec.push((11.0, 12.0));

        self.selected_pos_tuple_vec = &self.second_pos_tuple_vec;
    }
}

fn main() {}

error[E0495]: cannot infer an appropriate lifetime for borrow expression due to conflicting requirements
  --> src/main.rs:24:39
   |
24 |         self.selected_pos_tuple_vec = &self.second_pos_tuple_vec;
   |                                       ^^^^^^^^^^^^^^^^^^^^^^^^^^
   |
note: first, the lifetime cannot outlive the anonymous lifetime #1 defined on the method body

This is not possible with references. A struct can only hold references to things stored outside the struct. In this case, I would probably just stored an enum that specifies which one is selected and provide a function that matches on the enum and returns the reference.

@alice is correct. The problem with storing a reference to a struct within the same struct is that, at the instant the struct is physically moved in memory, any such reference becomes an invalid, dangling reference. The rustc compiler protects you from such unsafe memory errors.

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.