How to update a element using another element in same vector

I need update all element of a vector with element in same vector that contains many big size data. demo code as follows:

pub struct BigData;
impl BigData {
    pub fn update(&mut self, d: &Self) {
    }
}

...
let mut data = vec![BigData{}; size];
//update
for idx in (0..data.len()).rev() {
    if idx > 0 {
        let pre_elm = &data[idx - 1];
         data[idx].update(pre_elm);    
     }
 }
...

this codes failed to compile because the data has been borrowed to pre_elm immutablely, but the fn data[idx].update() will borrow data mutablely, at same time also using pre_elm.
The size of element is big, make a copy is too expensive. Please help how should I do to solve this problem, thanks.

You can use the split_at_mut method on the vec to borrow its parts mutably in separate groups.

for idx in (0..data.len()).rev() {
    if idx > 0 {
        let (left, right) = data.split_at_mut(idx);
        right[0].update(&left[idx - 1]);
    }
}
3 Likes

Thanks, it works :grinning: