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

How do I shove a slice into an array?

let mut foo: [u8; 6] = &[0, 0, 0, 0, 0, 0]
let mut bar: &[u8] = &[1, 2, 3]

I want the desired result:

&[1, 2, 3, 0, 0, 0]

The obvious way:

let foo: [u8; 6] = [bar, vec![0; 6 - bar.len()].as_slice()].concat().try_into()...
  1. It causes a lot of overhead.
  2. It’s not practical

Perhaps there are some other ways?

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

>Solution :

Use copy_from_slice:

fn main() {
    let mut foo: [u8; 6] = [0, 0, 0, 0, 0, 0];
    let mut bar: &[u8] = &[1, 2, 3];
    
    println!("before: {:?}", foo); // [0, 0, 0, 0, 0, 0]
    
    foo[..bar.len()].copy_from_slice(bar);
    
    println!("after: {:?}", foo); // [1, 2, 3, 0, 0, 0]
}

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