An easy way to modify slice?

#![allow(unused)]
fn main() {
    let mut a = vec![0, 1, 2, 3, 4, 5];
    let a1 = vec![-1, -2];
    let a2 = vec![-10, -20];
    a[0..2] = *a1.as_slice();
    a[4..] = *a2.as_slice();

    println!("{:?}", a)
    // Expected: [-1, -2, 2, 3, -10, -20]
}

The compile error lead me to dynamically-sized-types-and-the-sized-trait, but I still dont know why a[0..2] cant be know the size at compile time, and how can I get what I expected.

You can use copy_from_slice:

    a[0..2].copy_from_slice(&a1);
    a[4..].copy_from_slice(&a2);
1 Like

Indexing with a range always returns the type [u8] no matter if the length is hard-coded or not, and this type is fundamentally something whose type is not known. It's true that you can figure out how large it is, but the compiler is not able to.

1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.