在 Rust 中连接向量的最佳方法 [英] Best way to concatenate vectors in Rust

查看:17
本文介绍了在 Rust 中连接向量的最佳方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

甚至可以在 Rust 中连接向量吗?如果是这样,有没有一种优雅的方式来做到这一点?我有这样的事情:

let mut a = vec![1, 2, 3];让 b = vec![4, 5, 6];对于 val in &b {a.push(val);}

有人知道更好的方法吗?

解决方案

结构 std::vec::Vec 有方法 append():

fn append(&mut self, other: &mut Vec<T>)

<块引用>

other 的所有元素移动到 Self 中,将 other 留空.

在您的示例中,以下代码将通过 mutating ab 连接两个向量:

fn main() {让 mut a = vec![1, 2, 3];让 mut b = vec![4, 5, 6];a.append(&mut b);assert_eq!(a, [1, 2, 3, 4, 5, 6]);assert_eq!(b, []);}

<小时>

或者,您可以使用 扩展::extend() 将可以转换为迭代器(如 Vec)的所有元素附加到给定的向量:

let mut a = vec![1, 2, 3];让 b = vec![4, 5, 6];a.扩展(b);assert_eq!(a, [1, 2, 3, 4, 5, 6]);//b 被移动,不能再使用

注意向量 b 被移动而不是被清空.如果您的向量包含实现 Copy 的元素,您可以将一个向量的不可变引用传递给 extend() 以避免移动.在这种情况下,向量 b 不会改变:

let mut a = vec![1, 2, 3];让 b = vec![4, 5, 6];a.extend(&b);assert_eq!(a, [1, 2, 3, 4, 5, 6]);assert_eq!(b, [4, 5, 6]);

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?

解决方案

The structure std::vec::Vec has method append():

fn append(&mut self, other: &mut Vec<T>)

Moves all the elements of other into Self, leaving other empty.

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, []);
}


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

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 中连接向量的最佳方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆