I would like to take a mutable slice and copy the contents into two new mutable slices. Each slice being one half of the original.
My attempt #1:
let
The split_at and split_at_mut methods will give you two slices, which you can then copy or even safely use without copying if borrow checker allows.
let (list_a, list_b) = my_list.split_at_mut(my_list.len()/2)
You can build vectors from slices directly by cloning the elements using multiple methods:
fn main() {
let my_list: &mut [u8] = &mut [0, 1, 2, 3, 4, 5];
let mut vec1 = my_list[0..2].to_vec();
let mut vec2: Vec<u8> = my_list[2..4].into();
let mut vec3 = my_list[2..6].to_owned();
println!("{:?}", vec1);
println!("{:?}", vec2);
}
Your original problem was caused because all of these return a Vec
but you were attempting to claim that it was a slice, equivalent to:
let thing: &mut [u8] = Vec::new();
You could chain two iterators over the slices.
let my_list: &mut [u8] = &mut [0, 1, 2, 3, 4, 5];
let mut slices = my_list[0..3].iter().chain(my_list[3..6].iter());
for e in slices {}
chain
will iterate over the first iterator, then the second.
To create new lists:
let my_list: &mut [u8] = &mut [0, 1, 2, 3, 4, 5];
let mut a: Vec<u8> = my_list[0..3].iter().cloned().collect();
let mut b: Vec<u8> = my_list[3..6].iter().cloned().collect();