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

后端 未结 3 650
眼角桃花
眼角桃花 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:13

    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)
    
    0 讨论(0)
  • 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<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();
    
    0 讨论(0)
  • 2020-12-18 00:19

    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();
    
    0 讨论(0)
提交回复
热议问题