[英]How do I get a slice of a Vec<T> in Rust?
I can not find within the documentation of Vec<T>
how to retrieve a slice from a specified range.我在
Vec<T>
的文档中找不到如何从指定范围检索切片。
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];
The documentation for Vec
covers this in the section titled "slicing" . Vec
的文档在标题为“切片”的部分中涵盖了这一点。
You can create a slice
of a Vec
or array
by indexing it with a Range
(or RangeInclusive
, RangeFrom
, RangeTo
, RangeToInclusive
, or RangeFull
), for example :您可以通过使用
Range
(或RangeInclusive
、 RangeFrom
、 RangeTo
、 RangeToInclusive
或RangeFull
)对其进行索引来创建Vec
或array
的slice
, 例如:
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[..]);
}
If you wish to convert the entire Vec
to a slice, you can use deref coercion :如果您希望将整个
Vec
转换为切片,您可以使用deref coercion :
fn main() {
let a = vec![1, 2, 3, 4, 5];
let b: &[i32] = &a;
println!("{:?}", b);
}
This coercion is automatically applied when calling a function:调用函数时会自动应用此强制:
fn print_it(b: &[i32]) {
println!("{:?}", b);
}
fn main() {
let a = vec![1, 2, 3, 4, 5];
print_it(&a);
}
You can also call Vec::as_slice
, but it's a bit less common:您也可以调用
Vec::as_slice
,但它不太常见:
fn main() {
let a = vec![1, 2, 3, 4, 5];
let b = a.as_slice();
println!("{:?}", b);
}
See also:另见:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.