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()...
Perhaps there are some other ways?
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 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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With