我如何获得一片 Vec<T>在锈? [英] How do I get a slice of a Vec<T> in Rust?
本文介绍了我如何获得一片 Vec<T>在锈?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在 Vec
的文档中找不到如何从指定范围检索切片.
I can not find within the documentation of Vec<T>
how to retrieve a slice from a specified range.
标准库中有没有这样的东西:
Is there something like this in the standard library:
let a = vec![1, 2, 3, 4];
let suba = a.subvector(0, 2); // Contains [1, 2];
推荐答案
Vec
的文档在 标题为切片"的部分.
您可以创建一个slice
Vec
或 array
通过使用 Range
(或 RangeInclusive
, RangeFrom
, RangeTo
, RangeToInclusive
或 RangeFull
)、例如:
fn main() {
let a = vec![1, 2, 3, 4, 5];
// With a start and an end
println!("{:?}", &a[1..4]);
// With a start and an end, inclusive
println!("{:?}", &a[1..=3]);
// With just a start
println!("{:?}", &a[2..]);
// With just an end
println!("{:?}", &a[..3]);
// With just an end, inclusive
println!("{:?}", &a[..=2]);
// All elements
println!("{:?}", &a[..]);
}
这篇关于我如何获得一片 Vec<T>在锈?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文