Assign values to slice of array

I have the following code:

const FOO: [u8; 5] = [0, 1, 2, 3, 4];

fn main() {
    let mut bar: [u8; 10] = [0; 10];

    // I want bar to be [0, 1, 2, 3, 4, 5, 0, 0, 0, 0, 0]

    // None of these work
    bar = FOO;
    bar = FOO[..];
    bar = &FOO[..];
    &bar[0..5] = FOO;
    &bar[0..5] = &FOO[0..5];
    &mut bar[0..5] = &mut FOO[0..5];

    // Works, but feels unnecessary complex
    for (count, &byte) in FOO.iter().enumerate() {
        bar[count] = byte;

Is there a way to make it so that bar contains a copy of each element of FOO, and then some more elements ?

I've tried many variations of "bar = FOO", but none of these seem to work, since either the types don't match, or the left-side of assignment is invalid.

I could use a loop, but that feels unnecessary complex for an operation that seems pretty straightforward to me

Is there a simple way to do this ?

A single loop hardly counts as "complex".

However, there is a dedicated method on slices for this, copy_from_slice. I.e., bar[..FOO.len()].copy_from_slice(&FOO);

1 Like

I would probably do something like:

(0..5).chain([0; 5])

But, your problem does seem like an XY problem.

Nightly alternative to @H2CO3's solution:

// ...
*bar.array_chunks_mut().nth(0).unwrap() = FOO;

Another one:


bar.as_chunks_mut().0[0] = FOO;
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.