Multiple mutable references to disjoint parts of a slice using split_mut or similar

Rust's split_mut function allows you to split a slice by a predicate. However, the predicate acts on elements of the slice. Example:

let mut v = [10, 40, 30, 20, 60, 50];

for group in v.split_mut(|num| *num % 3 == 0) {
    group[0] = 1;
assert_eq!(v, [1, 40, 30, 1, 60, 1]);

Can I split a slice in equal parts like this:

let mut v = [1,2,3,4,5,6,7,8,9];

and get

&mut[1,2,3] and &mut[4,5,6] and &mut[7,8,9]

in usch that all these mutables can exist in the same time without me having compilation problems? I want to have multiple mutable references to disjoint parts of a slice, but the predicate should be on the index of the slice, not the elements.

You can do this by repeatedly calling split_at_mut repeatedly. Alternatively, you can define a local variable i to count the iteration and use that in the closure.

If you literally need fixed-size slices, there's chunks_mut(3).

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.