如何在Rust中连接两个切片?

栏目: 编程语言 · Rust · 发布时间: 7年前

内容简介:翻译自:https://stackoverflow.com/questions/40154150/how-do-i-concatenate-two-slices-in-rust

我想从向量中获取x个第一个和最后一个元素并将它们连接起来.我有以下代码:

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.

你应该使用skip()的gather()ed结果收集()take()和extend()它们的结果:

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会这样做,因为它是迭代器).

编辑2:你的数字有点偏;为了获得1,2,3,8,9,10,你应该声明v如下:

let v = (1u64 .. 11).collect::<Vec<_>>();

由于 Range 是左关闭和右开.

翻译自:https://stackoverflow.com/questions/40154150/how-do-i-concatenate-two-slices-in-rust


以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Visual Thinking

Visual Thinking

Colin Ware / Morgan Kaufmann / 2008-4-18 / USD 49.95

Increasingly, designers need to present information in ways that aid their audiences thinking process. Fortunately, results from the relatively new science of human visual perception provide valuable ......一起来看看 《Visual Thinking》 这本书的介绍吧!

HTML 压缩/解压工具
HTML 压缩/解压工具

在线压缩/解压 HTML 代码

Base64 编码/解码
Base64 编码/解码

Base64 编码/解码

Markdown 在线编辑器
Markdown 在线编辑器

Markdown 在线编辑器