I almost have a way to access a struct &mut reference var so I can use it throughout an app for decisions, but when I swap reference assignments in the following code:
pub struct X {
pub first_pos_tuple_vec: Vec<(f64, f64)>,
pub second_pos_tuple_vec: Vec<(f64, f64)>,
}
impl X {
pub fn new() -> X {
X {
first_pos_tuple_vec: Vec::new(),
second_pos_tuple_vec: Vec::new(),
}
}
}
pub struct References<'a> {
pub selected_pos_tuple_vec: Option<&'a mut Vec<(f64, f64)>>,
}
impl<'a> References<'a> {
pub fn new() -> References<'static> {
References {
selected_pos_tuple_vec: None,
}
}
}
fn main() {
let mut x = X::new();
x.first_pos_tuple_vec.push((3.0, 4.0));
x.first_pos_tuple_vec.push((5.0, 6.0));
x.second_pos_tuple_vec.push((7.0, 8.0));
x.second_pos_tuple_vec.push((9.0, 10.0));
x.second_pos_tuple_vec.push((11.0, 12.0));
let mut refs = References::new();
refs.selected_pos_tuple_vec = Some(&mut x.second_pos_tuple_vec);
println!(
"refs.selected_pos_tuple_vec = {:?}",
refs.selected_pos_tuple_vec
);
refs.selected_pos_tuple_vec = Some(&mut x.first_pos_tuple_vec);
println!(
"refs.selected_pos_tuple_vec = {:?}",
refs.selected_pos_tuple_vec
);
if let Some(tuplevec) = refs.selected_pos_tuple_vec {
println!("tuplevec = {:?}", tuplevec[0].0);
}
refs.selected_pos_tuple_vec = Some(&mut x.second_pos_tuple_vec);
if let Some(tuplevec) = refs.selected_pos_tuple_vec {
println!("tuplevec = {:?}", tuplevec[0].0);
}
}
this error is produced:
error[E0499]: cannot borrow `x.second_pos_tuple_vec` as mutable more than once at a time
--> src/main.rs:54:40
|
38 | refs.selected_pos_tuple_vec = Some(&mut x.second_pos_tuple_vec);
| --------------------------- first mutable borrow occurs here
...
54 | refs.selected_pos_tuple_vec = Some(&mut x.second_pos_tuple_vec);
| -----------------------------------^^^^^^^^^^^^^^^^^^^^^^^^^^^-
| | |
| | second mutable borrow occurs here
| first borrow later used here
How do I get around this?