gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 19:39:49 26 4
gpt4 key购买 nike

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

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);
}

关于arrays - 如何连接已知长度的数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67041830/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com