如何在 Rust 中连接两个切片? [英] How do I concatenate two slices in Rust?
问题描述
我想从向量中取出 x 的第一个和最后一个元素并将它们连接起来.我有以下代码:
I want to take the x first and last elements from a vector and concatenate them. I have the following code:
fn main() {
let v = (0u64 .. 10).collect::<Vec<_>>();
let l = v.len();
vec![v.iter().take(3), v.iter().skip(l-3)];
}
这给了我错误
error[E0308]: mismatched types
--> <anon>:4:28
|
4 | vec![v.iter().take(3), v.iter().skip(l-3)];
| ^^^^^^^^^^^^^^^^^^ expected struct `std::iter::Take`, found struct `std::iter::Skip`
<anon>:4:5: 4:48 note: in this expansion of vec! (defined in <std macros>)
|
= note: expected type `std::iter::Take<std::slice::Iter<'_, u64>>`
= note: found type `std::iter::Skip<std::slice::Iter<'_, u64>>`
如何获得 1、2、3、8、9、10
的 vec
?我使用的是 Rust 1.12.
How do I get my vec
of 1, 2, 3, 8, 9, 10
? I am using Rust 1.12.
推荐答案
你应该 collect()
take()
和 extend() 的结果
将它们与 skip()
的 collect()
ed 结果:
You should collect()
the results of the take()
and extend()
them with the collect()
ed results of skip()
:
let mut p1 = v.iter().take(3).collect::<Vec<_>>();
let p2 = v.iter().skip(l-3);
p1.extend(p2);
println!("{:?}", p1);
编辑:正如 Neikos 所说,你甚至不需要收集 skip()
的结果,因为 extend()
接受实现 IntoIterator
的参数(Skip
这样做,因为它是一个 Iterator
).
Edit: as Neikos said, you don't even need to collect the result of skip()
, since extend()
accepts arguments implementing IntoIterator
(which Skip
does, as it is an Iterator
).
编辑 2:不过,您的数字有点偏差;为了得到 1, 2, 3, 8, 9, 10
你应该声明 v
如下:
Edit 2: your numbers are a bit off, though; in order to get 1, 2, 3, 8, 9, 10
you should declare v
as follows:
let v = (1u64 .. 11).collect::<Vec<_>>();
由于Range
是左闭右开.
Since the Range
is left-closed and right-open.
这篇关于如何在 Rust 中连接两个切片?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!