To remove an item at a specific index from a vector in Rust, you can use the remove
method or by using the split_off
method.
In this example,
vec
with some integer values.index_to_remove
.remove
method to remove the item at the specified index. The remove
method takes the index as an argument and removes the element at that index, shifting all elements after it to the left.remove
method also returns the removed element, but we can ignore it if not needed.fn main() {
let mut vec = vec![10, 20, 30, 40, 50];
let index_to_remove = 2;
vec.remove(index_to_remove);
println!("Vector after removing the item at index {}: {:?}", index_to_remove, vec);
}
Vector after removing the item at index 2: [10, 20, 40, 50]
In this example,
vec
with some integer values.index_to_remove
.split_off
method to split the vector at the specified index. The split_off
method takes an index and splits the vector into two: the original vector contains elements up to (but not including) the specified index, and the method returns a new vector with elements from the specified index onwards.append
method.fn main() {
let mut vec = vec![10, 20, 30, 40, 50];
let index_to_remove = 2;
let mut tail = vec.split_off(index_to_remove);
tail.remove(0);
vec.append(&mut tail);
println!("Vector after removing the item at index {}: {:?}", index_to_remove, vec);
}
Vector after removing the item at index 2: [10, 20, 40, 50]
In this tutorial, we learned How to Remove Item at a Specific Index from a Vector in Rust language with well detailed examples.