Copy array slice into another array slice

In a buffer implementation, I would like to copy an array slice into another array slice.

static X: [u8; 10] = [ 1,2,3,4,5,6,7,8,9,10 ];

fn main() {
    let mut y: [u8; 20] = [0; 20];
    &X[1 .. 2].clone_into(&mut y[0 .. 1]);

I do get

error[E0308]: mismatched types
  --> src/
13 |     &X[1 .. 2].clone_into(&mut y[0 .. 1]);
   |                ---------- ^^^^^^^^^^^^^^ expected `&mut Vec<u8>`, found `&mut [u8]`
   |                |
   |                arguments to this method are incorrect
   = note: expected mutable reference `&mut Vec<u8>`
              found mutable reference `&mut [u8]`

However, I don't want a Vec, in the end the copying will happen from and to parts of fixed-sized arrays.

How can I achieve this?


Rust Playground

1 Like

clone_into() only works with general Clone types that are Sized, which slices aren't, so the compiler picks up the explicit impl for [T] instead, and [T]::Owned is Vec<T>.

You probably want <[T]>::clone_from_slice().

1 Like

No, that does something completely different.

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.