Insert An Element At A Specific Index In An Array In Rust
Code snippet for how to Insert An Element At A Specific Index In An Array In Rust with sample and detail explanation
In this article, we’ll explore how to insert an element at a specific index in an array in Rust. This is an essential technique for manipulating array data structures in the Rust programming language.
Insert An Element At A Specific Index In An Array In Rust Code Snippet
Consider that we have a mutable array (in Rust called a vector) vec1
and we want to add an element element
at a certain position index
. Below is the Rust code to perform this operation:
fn main() {
let mut vec1 = vec![1, 2, 3, 4, 5];
let index = 2;
let element = 10;
vec1.insert(index, element);
println!("{:?}", vec1);
}
After executing the program, the output will be [1, 2, 10, 3, 4, 5]
.
Code Explanation for ‘Insert An Element At A Specific Index In An Array In Rust’
In this Rust code, we are modifying an array which is commonly referred to as a vector in Rust. We’ve chosen this because unlike arrays, vectors are resizable.
Firstly, we declare and initialize a mutable vector vec1
of integers: let mut vec1 = vec![1, 2, 3, 4, 5];
. It is important to note that the vector must be mutable, as we will be changing its content.
Next, we declare the variables ‘index’ and ‘element’. index
is the position where we want to insert new value, and element
is the value we wish to insert. As per our example, the index
is 2
and the element
is 10
.
vec1.insert(index, element);
is a built-in Rust function where we pass index
and element
, specifying the position and value of the new element we want to insert.
Finally, println!("{:?}", vec1);
is used to print the resulting vector after the insertion of our new element. The println!
macro uses ”:” to format the output, while ”?” prints out the Debug formatting of the vector.
Running this main function will yield a vector with the specified element added at the desired index. In our example, 10
is inserted at index 2
in vec1
and the modified vector is printed out as [1, 2, 10, 3, 4, 5]
.