如何连接已知长度的数组?

我有两个已知长度的数组:

let left: [u8; 2] = [1, 2];
let right: [u8; 3] = [3, 4, 5];

我的第一次尝试:

let whole: [u8; 5] = left + right;

失败并出现错误:

error[E0369]: cannot add `[u8; 2]` to `[u8; 3]`
  --> /home/fadedbee/test.rs:25:29
   |
25 |         let whole: [u8; 5] = left + right;
   |                              ---- ^ ----- [u8; 3]
   |                              |
   |                              [u8; 2]

同样地:

let whole: [u8; 5] = left.concat(right);

失败:

error[E0599]: the method `concat` exists for array `[u8; 2]`, but its trait bounds were not satisfied
  --> /home/fadedbee/test.rs:25:29
   |
25 |         let whole: [u8; 5] = left.concat(right);
   |                                   ^^^^^^ method cannot be called on `[u8; 2]` due to unsatisfied trait bounds
   |
   = note: the following trait bounds were not satisfied:
           `<[u8] as std::slice::Concat<_>>::Output = _`

我目前正在使用以下形式的表达式:

let whole: [u8; 5] = [left[0], left[1], right[0], right[1], right[2]];

但这对于我的实际用例来说是几十个元素,并且容易出现拼写错误。

@Emoun 好心地指出我误用了concat.

正确尝试:

 let whole: [u8; 5] = [left, right].concat();

我得到:

error[E0308]: mismatched types
  --> /home/fadedbee/test.rs:32:31
   |
32 |         let whole: [u8; 5] = [left, right].concat();
   |                                     ^^^^^ expected an array with a fixed size of 2 elements, found one with 3 elements
   |
   = note: expected type `[u8; 2]`
             found array `[u8; 3]`

如何将已知长度的数组连接成一个固定长度的数组?

回答

我想有一个更好的答案,但你可以这样做:

fn main() {
    let left: [u8; 2] = [1, 2];
    let right: [u8; 3] = [3, 4, 5];

    let whole: [u8; 5] = {
        let mut whole: [u8; 5] = [0; 5];
        let (one, two) = whole.split_at_mut(left.len());
        one.copy_from_slice(&left);
        two.copy_from_slice(&right);
        whole
    };

    println!("{:?}", whole);
}


以上是如何连接已知长度的数组?的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>