乐闻世界logo
搜索文章和话题

How do I get a slice of a Vec< T > in Rust?

1个答案

1

In Rust, you can obtain a slice from a Vec<T> using the range operator ... A slice is a view (or reference) of the underlying data and does not own the data. The basic syntax for obtaining a slice is &vector[start..end], where start is the starting index (inclusive) and end is the ending index (exclusive). Indices are zero-based.

Here is a simple example demonstrating how to obtain a slice from a vector:

rust
fn main() { let vec = vec![1, 2, 3, 4, 5]; // Obtain a slice starting at index 1 and ending at index 3 (exclusive) let slice = &vec[1..3]; // Print the slice, which outputs: [2, 3] println!("{:?}", slice); }

In this example, vec is a vector containing integers. Using the expression &vec[1..3], we obtain a slice starting at index 1 and ending at index 3 (exclusive), resulting in a slice containing elements 2 and 3.

Notably, if you attempt to access an index beyond the vector's length, Rust will panic at runtime, so it's typically necessary to ensure indices are within the valid range.

Additionally, you can use the .. operator to omit the start or end index for convenience, representing slices from the beginning to a certain index or from a certain index to the end:

rust
// From the beginning to index 2 (exclusive) let slice_start = &vec[..2]; // From index 2 to the end let slice_end = &vec[2..]; // Print the slices println!("slice_start: {:?}", slice_start); // Output: [1, 2] println!("slice_end: {:?}", slice_end); // Output: [3, 4, 5]

In this way, you can flexibly obtain the required data segments from the vector.

2024年8月7日 17:03 回复

你的答案