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.rs347 chars9 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