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

后端 未结 3 652
眼角桃花
眼角桃花 2020-12-17 23:31

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         


        
3条回答
  •  失恋的感觉
    2020-12-18 00:17

    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 = 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();
    

提交回复
热议问题