OneBite.Dev - Coding blog in a bite size

Insert An Element At The End Of An Array In Rust

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

Adding elements at the end of an array is a routine operation in any programming language. In Rust, this task is not just straightforward but also very safe due to the built-in safeguards that prevent common problems such as memory overflow.

Code snippet: Adding an element at the end of an array in Rust

fn main() {
    let mut array = vec![11, 22, 33, 44, 55]; 
    array.push(66);
    println!("{:?}", array);
}

In this simple code snippet, we’re declaring a vector and pushing a value to the end of it.

Code Explanation for Adding an element at the end of an array in Rust

The first line of our code snippet reads fn main() {. In Rust, all programs need a function named main where execution begins.

The second line, let mut array = vec![11, 22, 33, 44, 55], declares a mutable variable named “array”. This variable is assigned a vector containing five elements. The mut keyword is mandatory because we’re going to alter the array by adding another element to it. Without using mut, Rust’s borrow checker won’t let us modify the array.

The third line is where we add the new element. array.push(66) pushes the integer 66 at the end of the vector. The push method is Rust’s built-in function for adding an element at the end of a vector.

The last line of the code, println!("{:?}", array);, prints the array, now containing six elements exactly as we intended. The "{:?}" inside println! is a placeholder that gets replaced by the value of array.

rust