如何连接两个切片或两个向量并仍然可以访问原始值? [英] How can I concatenate two slices or two vectors and still have access to the original values?

查看:24
本文介绍了如何连接两个切片或两个向量并仍然可以访问原始值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个切片或向量,我想添加它们,如 Golang 中所示:

I have two slice or vectors and I want to add them, as demonstrated here in Golang:

a := []byte{1, 2, 3}
b := []byte{4, 5, 6}
ab := append(a, b...)
ba := append(b, a...)

我怎样才能在 Rust 中做到这一点?我发现了一些其他问题,例如:

How can I do that in Rust? I found some other questions, such as:

但是,他们所有的最佳答案都是a += b,而不是ab = a + b.

but, all of their best answer is a += b, and not ab = a + b.

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

或者在 Rust 中是否有像 Vec::append(a, b) 这样的函数?

Or is there maybe a function like Vec::append(a, b) in Rust?

推荐答案

您可以chain 你的迭代器:

You can chain your iterators:

fn main() {
    let a = vec![1, 2, 3];
    let b = vec![4, 5, 6];

    // Don't consume the original vectors and clone the items:
    let ab: Vec<_> = a.iter().chain(&b).cloned().collect();

    // Consume the original vectors. The items do not need to be cloneable:
    let ba: Vec<_> = b.into_iter().chain(a).collect();

    assert_eq!(ab, [1, 2, 3, 4, 5, 6]);
    assert_eq!(ba, [4, 5, 6, 1, 2, 3]);
}

注意迭代器知道它产生的项目数,以便collect可以直接分配合适的内存量:

Note that the iterator knows the number of items that it yields, so that collect can allocate directly the right amount of memory:

fn main() {
    let a = vec![1, 2, 3];
    let b = vec![4, 5, 6];

    let ba = b.into_iter().chain(a);
    assert_eq!(ba.size_hint(), (6, Some(6)));

    let ba: Vec<_> = ba.collect();
    assert_eq!(ba, [4, 5, 6, 1, 2, 3]);
}

这篇关于如何连接两个切片或两个向量并仍然可以访问原始值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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