如何在 Rust 中获得一片 Vec < T > ?

我无法在 Vec<T>的文档中找到如何从指定范围检索切片的方法。

在标准库中是否有类似的东西:

let a = vec![1, 2, 3, 4];
let suba = a.subvector(0, 2); // Contains [1, 2];
109055 次浏览

The documentation for Vec covers this in the section titled "slicing".

You can create a slice of a Vec0 or Vec1 by indexing it with a Vec2 (or Vec3, Vec4, Vec5, Vec6, or Vec7), Vec8:

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:

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:

fn main() {
let a = vec![1, 2, 3, 4, 5];
let b = a.as_slice();
println!("{:?}", b);
}

See also: