How do I create two new mutable slices from one slice?

久未见 提交于 2019-12-01 04:34:01
snf

You can build vectors from slices directly by cloning the elements using multiple methods:

  1. Vec::to_vec
  2. From / Into
  3. ToOwned
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();
Kornel

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)
A.B.

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();
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!