Elias
Elias

Reputation: 4112

Copying elements of a slice into a new array

Is there a nice way of creating an array (that already has elements) and copy the elements of another slice into it?

I thought of maybe sort-of destructuring it?

fn main() {
    let cmd: u8 = 1;
    let config: &[u8; 2] = &[2, 3];
    let bytes = &[cmd, ..config];
}

Playground (does not work - what I would like to do)

Basically, is there some syntactical sugar for either:

fn main() {
    let cmd: u8 = 1;
    let config: &[u8; 2] = &[2, 3];

    let mut bytes: [u8; 3] = [0; 3];
    bytes[0] = cmd;
    bytes[1..].copy_from_slice(config);
    
    println!("{:?}", bytes);
}

Playground

or

fn main() {
    let cmd: u8 = 1;
    let config: &[u8; 2] = &[2, 3];
    let bytes = [cmd, config[0], config[1]];
    
    println!("{:?}", bytes);
}

Playground

Upvotes: 0

Views: 211

Answers (1)

Chayim Friedman
Chayim Friedman

Reputation: 70860

No there is not. copy_from_slice() is the right way to go.

Upvotes: 1

Related Questions