In Rust, you can split a vector into smaller parts using various methods such as iteration, slicing, or using external libraries like itertools.
In this example,
data
containing elements.&data[start_index..end_index]
to extract the subvector.fn main() {
let data = vec![1, 2, 3, 4, 5, 6];
let split_index = 3;
let (left, right) = data.split_at(split_index);
println!("Left part: {:?}", left);
println!("Right part: {:?}", right);
}
Left part: [1, 2, 3] Right part: [4, 5, 6]
In this example,
data
containing elements.iter()
method to iterate over the vector and filter elements based on the predicate.fn main() {
let data = vec![1, 2, 3, 4, 5, 6];
let split_predicate = |&x| x > 3;
let (left, right): (Vec<_>, Vec<_>) = data.into_iter().partition(split_predicate);
println!("Left part: {:?}", left);
println!("Right part: {:?}", right);
}
Left part: [4, 5, 6] Right part: [1, 2, 3]
In this tutorial, we learned How to Split a Vector in Rust language with well detailed examples.