remove an element from an array at a specific index in rust

To remove an element from an array at a specific index in Rust, you need to make the array mutable so that you can change its contents. Here's an example:

main.rs
fn main() {
    let mut arr = [1, 2, 3, 4, 5];
    let index = 2; // index of element to remove
    let removed_element = arr.remove(index); // remove element and store it in a variable
    
    println!("Array after removing element: {:?}", arr); // will print [1, 2, 4, 5]
    println!("Removed element: {}", removed_element); // will print 3
}
347 chars
9 lines

In this example, we create an array arr and make it mutable by adding the mut keyword. We also define the index of the element to remove (2).

To actually remove the element, we use the remove method on the array and pass in the index as an argument. This method will remove the element at the given index and shift all the remaining elements to fill the gap.

The remove method returns the removed element, which we store in the removed_element variable. Finally, we print the array after the removal (which will be [1, 2, 4, 5]) and the removed element (which will be 3).

gistlibby LogSnag