英文:
How do I shove a slice into an array?
问题
&[1, 2, 3, 0, 0, 0]
英文:
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()...
- It causes a lot of overhead.
- It's not practical
Perhaps there are some other ways?
答案1
得分: 6
使用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]
}
英文:
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]
}
答案2
得分: 4
像这样:
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 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);
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论