Borrowing two different parts of a vec

                    let mut tmps = vec![vec![0_i32; n]; 2];
                    let i = 20;
                    let rhs = &tmps[(i + 1) % 2];
                    let res = &mut tmps[i % 2];

I'm doing something of the form:

  for x in lst {
    new_value = f(x, old_value);
    swap storage for new_value, old_value

I'm trying to use the tmps to store both old_value and new_value -- and running into this borrow issue. I understand where the compiler is coming from (i'ts not seeing the %2 as mutually exclusive).

What is the idiomatic way to resolve this ?

The only safe way to split it is to use split_at_mut or one of the similar methods.

let (rhs, res) = {
    let (a, b) = tmps.split_at_mut(1);
    if i % 2 == 1 {
        (&a[0], &mut b[0])
    } else {
        (&b[0], &mut a[0])

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.