问题描述
是否有可能在Rust中连接向量?如果是这样,是否有一种优雅的方法?我有这样的东西:
Is it even possible to concatenate vectors in Rust? If so, is there an elegant way to do so? I have something like this:
let mut a = vec![1, 2, 3];
let b = vec![4, 5, 6];
for val in &b {
a.push(val);
}
有人知道更好的方法吗?
Does anyone know of a better way?
推荐答案
结构 std :: vec :: Vec
具有方法:
The structure std::vec::Vec
has method append()
:
fn append(&mut self, other: &mut Vec<T>)
在您的示例中,以下代码通过变异 a
和 b
:
From your example, the following code will concatenate two vectors by mutating a
and b
:
fn main() {
let mut a = vec![1, 2, 3];
let mut b = vec![4, 5, 6];
a.append(&mut b);
assert_eq!(a, [1, 2, 3, 4, 5, 6]);
assert_eq!(b, []);
}
或者,您可以使用将可以转换为迭代器(例如 Vec
)的所有元素附加到给定向量:
Alternatively, you can use Extend::extend()
to append all elements of something that can be turned into an iterator (like Vec
) to a given vector:
let mut a = vec![1, 2, 3];
let b = vec![4, 5, 6];
a.extend(b);
assert_eq!(a, [1, 2, 3, 4, 5, 6]);
// b is moved and can't be used anymore
请注意,向量 b
被移动而不是清空。如果您的向量包含实现,您可以将对一个向量的不可变引用传递给 extend()
,以避免移动。在这种情况下,向量 b
不变:
Note that the vector b
is moved instead of emptied. If your vectors contain elements that implement Copy
, you can pass an immutable reference to one vector to extend()
instead in order to avoid the move. In that case the vector b
is not changed:
let mut a = vec![1, 2, 3];
let b = vec![4, 5, 6];
a.extend(&b);
assert_eq!(a, [1, 2, 3, 4, 5, 6]);
assert_eq!(b, [4, 5, 6]);
这篇关于在Rust中串联向量的最佳方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!