Reputation: 4112
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);
}
or
fn main() {
let cmd: u8 = 1;
let config: &[u8; 2] = &[2, 3];
let bytes = [cmd, config[0], config[1]];
println!("{:?}", bytes);
}
Upvotes: 0
Views: 211
Reputation: 70860
No there is not. copy_from_slice()
is the right way to go.
Upvotes: 1