Mut ref to two elements of a slice

Suppose we have:

let mut x: [[T; 100]; 200] = ...

Suppose furthermore, we want:

let mut r1 = &mut x[i+1][j+2];
let mut r2 = &mut x[i+2][j+3];

This clearly "can not work" since we can't borrow x mutably twice in the same context. Is there a way to make this happen?

Aside: Yes, I'm 100% sure they are disjoint. No, they are not specified at compile time. It's literally there exists indices i, j where we want items (i+1, j+2) and item (i+2, j+3)

In general, you can try to use split_at_mut or split_first_mut. For your particular case where the elements are adjacent, you can also use slice patterns, i.e.:

fn foo<T>(x: &mut [[T; 100]; 200], i: usize, j: usize) {
    let (r1, r2) = if let [s1, s2, ..] = &mut x[i + 1..] {
        (&mut s1[j + 2], &mut s2[j + 3])
    } else {
        panic!("…");
    };
    // etc.. use `r1` and `r2`
}
3 Likes

In this case, the simplest way to split it is probably this:

let (left, right) = x[i+1..].split_at_mut(1);
let mut r1 = &mut left[0][j+2];
let mut r2 = &mut right[0][j+3];
4 Likes

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.