add an element to the beginning of an array in rust

To add an element to the beginning of an array in Rust, you need to make sure you are using a mutable array. Once you have a mutable array, you can use array indexing to add an element at the beginning.

Here's an example:

main.rs
fn main() {
   let mut my_array = [1, 2, 3, 4, 5];
   let new_element = 0;
   for i in (1..my_array.len()).rev() {
       my_array[i] = my_array[i-1];
   }
   my_array[0] = new_element;
   println!("{:?}", my_array);
}
219 chars
10 lines

In this example, we first create a mutable array my_array and a new element new_element that we want to add to the beginning of the array.

Next, we iterate over the indices of the array in reverse order (using the rev() method) and shift each element to the right by one index. This makes room at the beginning of the array for the new element.

Finally, we assign the new element to the first index of the array and print out the updated array.

This should output:

main.rs
[0, 1, 2, 3, 4, 5]
19 chars
2 lines

gistlibby LogSnag