如何将一个切片插入到一个数组中?

huangapple go评论57阅读模式
英文:

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()...
  1. It causes a lot of overhead.
  2. 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);
}

huangapple
  • 本文由 发表于 2023年2月10日 05:29:51
  • 转载请务必保留本文链接:https://go.coder-hub.com/75404597.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定