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

Viewed 204

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.

1 Answers

As suggested by Jmb

You can use split_at_mut to divide a mutable slice into 2 non overlapping mutable slices.

fn main() {
    let mut v = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

    // Needs to be a multiple of v
    let number_of_parts = 5;

    let mid = v.len() / number_of_parts;

    let mut res = Vec::new();

    let mut ret = &mut v[..];

    for _ in 0..number_of_parts {
        let (head, tail) = ret.split_at_mut(mid);
        res.push(head);
        ret = tail;
    }

    println!("Parts: {:?}.", res);
}

As Suggested by Õmer Erden

You can use chunks_mut to iterate over a mutable slice an return non overlapping mutable slices.

fn main() {
    let mut v = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

    // Needs to be a multiple of v
    let number_of_parts = 5;

    let mid = v.len() / number_of_parts;

    let mut res = Vec::new();

    for chunk in v.chunks_mut(mid) {
        res.push(chunk);
    }

    println!("Parts: {:?}.", res);
}

Related