OneBite.Dev - Coding blog in a bite size

Insert An Element At The Beginning Of An Array In Rust

Code snippet for how to Insert An Element At The Beginning Of An Array In Rust with sample and detail explanation

In this article, we will discuss a simple way to insert an element at the beginning of an array in Rust, which is a statically typed, systems-oriented language focused on safety and performance. This topic is an essential part of the task in learning and understanding the data structure and Rust language.

Code Snippet: Insert an Element at the Beginning of an Array in Rust

The first step is to provide a simple code snippet to insert an item at the beginning of the array.

fn main() {
    let mut arr = vec![1, 2, 3, 4, 5];
    println!("Before insertion: {:?}", arr);

    arr.insert(0, 0);
    println!("After insertion: {:?}", arr);
}

This script will output the following:

Before insertion: [1, 2, 3, 4, 5]
After insertion: [0, 1, 2, 3, 4, 5]

Code Explanation: Insert an Element at the Beginning of an Array in Rust

In Rust, we can use the built-in method insert() to add an element at a specific index of an array. This method takes in two parameters: the index location where the new item needs to be added and the item itself.

Let’s dissect each part of the code snippet to understand how it works:

  • let mut arr = vec![1, 2, 3, 4, 5]; This line of code initializes a mutable vector arr with numbers from 1 to 5. Note that we used the vec! macro for creating a vector because arrays in Rust have a fixed size, and there’s no direct way to add elements to an array at runtime.

  • println!("Before insertion: {:?}", arr); This statement will print the original vector on the console: “Before insertion: [1, 2, 3, 4, 5]“.

  • arr.insert(0, 0); This piece of Rust’s method uses to add an element ‘0’ at the index position ‘0’. This means the number ‘0’ will now be at the first position of the array.

  • println!("After insertion: {:?}", arr); Finally, we print the array after insertion, which should yield: “After insertion: [0, 1, 2, 3, 4, 5]“. This confirms that the insert function successfully added the new item to the beginning of the arr vector.

Also, remember that the insert() function pushes all elements starting from the index to the right, increasing the size of the vector by one. Because of this behavior, the insertion operation has a time complexity of O(n), where n is the length of the array.

rust