Add New Item In Array In Rust
Code snippet for how to Add New Item In Array In Rust with sample and detail explanation
Rust, a systems programming language, offers several ways of working with arrays, including the ability to add new items. In this article, we’ll demonstrate a simple, yet effective approach on how to add a new item in an array in Rust.
Code Snippet: Adding New Item in Array
Here is a simple code snippet showing how to add a new item into an array using Rust:
fn main() {
let mut array = [1, 2, 3, 4];
array.push(5);
println!("{:?}", array);
}
Code Explanation for Adding New Item in Array
Firstly, we define our main function using fn main()
. Inside the main function, we declare a mutable array with initial elements 1, 2, 3, and 4, using let mut array = [1, 2, 3, 4];
.
The mut
keyword is used to indicate that the array variable can be modified after its initial declaration, which is essential as we’re looking to add an item to the array after its original definition.
Next, we use the push
method to append an element to the end of the array, using array.push(5);
. The push
method takes one argument, which is the item to be added at the end of the array.
The println!
macro is then used to print out the new array to the console, using println!("{:?}", array);
. The ”{:?}” is a placeholder for the array.
The code execution in the main function starts from top to bottom, therefore, the result from the console will show the new array, [1, 2, 3, 4, 5].
By using these Rust features and methods, you can effectively add new items to your arrays and manipulate your data as needed.