如何连接两个切片或两个向量,并且仍然可以访问原始值? [英] How can I concatenate two slices or two vectors and still have access to the original values?
本文介绍了如何连接两个切片或两个向量,并且仍然可以访问原始值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有两个切片或向量,我想将它们相加,如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屋!
查看全文