Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I shove a slice into an array?

Tags:

rust

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?

like image 209
Alexey Mirano Avatar asked Jun 02 '26 14:06

Alexey Mirano


2 Answers

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]
}

like image 158
PitaJ Avatar answered Jun 05 '26 03:06

PitaJ


Like so:

fn main() {

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

  foo[..3].clone_from_slice(bar);

  println!("{:?}", foo);
}
like image 23
Lagerbaer Avatar answered Jun 05 '26 05:06

Lagerbaer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!