OneBite.Dev - Coding blog in a bite size

Append Item In Array In Rust

Code snippet for how to Append Item In Array In Rust with sample and detail explanation

Appending items in an array in Rust can be a fundamental task when dealing with data collection in programming. This article discusses a step-by-step guide on appending items to an array using Rust’s built-in methods.

Code snippet for Appending item in Array in Rust

Below is a simple code snippet illustrating how to append items to an array in Rust.

fn main() {
    let mut array = vec![1, 2, 3, 4, 5];
    array.push(6);
    println!("Updated array: {:?}", array);
}

This script should output: Updated array: [1, 2, 3, 4, 5, 6].

Code Explanation for Appending Item in Array in Rust

Here’s a step-by-step breakdown of the above Rust code snippet:

  • We initialize the function ‘main()’ which kicks off our Rust program.
fn main() {
...
}
  • Inside this function, we initialize a mutable vector ‘array’ with five elements (1, 2, 3, 4, 5). It’s important to note that vectors in Rust can be augmented or reduced, unlike arrays. Hence, we use a ‘vec’ instead of an array for this function.
let mut array = vec![1, 2, 3, 4, 5];
  • Next, we use the ‘push’ method to append a new item to the end of our vector. The ‘push’ function in Rust automatically resizes the vector to accommodate the new element.
array.push(6);
  • Finally, we print out the updated vector to the console. The ”:?” inside the ‘println!’ macro is a placeholder for our vector ‘array’ and enables us to print each element of the array.
println!("Updated array: {:?}", array);

By the end of these few steps, you should have successfully appended an item to an array in Rust. It is crucial to remember that the ‘push’ function only works with mutable vectors, as Rust’s arrays are of fixed size.

rust