remove an element from the beginning of an array in rust

To remove an element from the beginning of an array in Rust, you need to mutate the array in place by slicing the array to remove the first element. Here is an example:

main.rs
fn main() {
    let mut arr = [1, 2, 3, 4, 5];
    let removed = arr[0]; // save the removed element if you need it
    arr = arr[1..]; // slice the array to remove the first element
    println!("Removed element: {}", removed);
    println!("Array after removal: {:?}", arr);
}
279 chars
8 lines

In this example, we first declare a mutable array arr with values [1, 2, 3, 4, 5]. We then extract the first element of the array by indexing it with arr[0] and save it in a variable removed in case we need it later. Finally, we mutate the array by slicing it with arr[1..] to remove the first element.

After removal, the array arr will now have the remaining elements [2, 3, 4, 5]. You can then print the removed element and the new state of the array using println!. Note that slicing an array in Rust will return a new array with the specified range, which is then assigned back to the original array to mutate it.

gistlibby LogSnag