Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading