To slice a vector in Rust, you can use the slicing syntax with the range operator `..`. This operator specifies a range from the starting index (inclusive) to the ending index (exclusive).
In this example,
v1
containing some elements.&v1[start..end]
to slice the vector from the start index (inclusive) to the end index (exclusive).// Slice a vector by index range
let v1 = vec![1, 2, 3, 4, 5];
let start = 1;
let end = 4;
let sliced_v1 = &v1[start..end];
println!("{:?}", sliced_v1); // Output: [2, 3, 4]
[2, 3, 4]
In this example,
v2
containing some elements.filter_map
method.// Slice a vector by logical condition
let v2 = vec![1, 2, 3, 4, 5];
let condition: Vec<bool> = v2.iter().map(|&x| x > 2).collect();
let sliced_v2: Vec<i32> = v2.iter().zip(condition.iter()).filter_map(|(&x, &c)| if c { Some(x) } else { None }).collect();
println!("{:?}", sliced_v2); // Output: [3, 4, 5]
[3, 4, 5]
In this tutorial, we learned How to Slice a Vector in Rust language with well detailed examples.