insert an element into an array at a specific index in rust

In Rust, arrays are fixed-size and have contiguous memory allocation. To insert an element into an array at a specific index, we need to create a new array with an additional element, copy the elements before the specified index from the old array to the new array, insert the new element, and then copy the elements after the specified index. Since arrays are immutable by default in Rust, we need to use a mutable array for this purpose.

Here's an example function that inserts an element at a specific index in an array:

main.rs
fn insert_element_at_index(array: &mut [i32], index: usize, element: i32) {
    let mut new_array = vec![0; array.len() + 1]; // create a new array with an additional element
    for i in 0..index { // copy the elements before the specified index
        new_array[i] = array[i];
    }
    new_array[index] = element; // insert the new element
    for i in index..array.len() { // copy the elements after the specified index
        new_array[i+1] = array[i];
    }
    *array = new_array; // assign the new array to the original array
}
538 chars
12 lines

This function takes a mutable slice of an integer array, an index at which to insert the element, and the element to insert. It creates a new integer vector of length array.len() + 1, copies the elements before the specified index from the original array to the new vector, inserts the new element at the specified index, and then copies the elements after the specified index from the original array to the new vector. Finally, it assigns the new vector to the original array.

Here's an example usage of this function:

main.rs
fn main() {
    let mut array = [1, 2, 3, 4, 5];
    insert_element_at_index(&mut array, 2, 6);
    println!("{:?}", array); // prints [1, 2, 6, 3, 4, 5]
}
156 chars
6 lines

gistlibby LogSnag