OneBite.Dev - Coding blog in a bite size

Copy An Array In Rust

Code snippet for how to Copy An Array In Rust with sample and detail explanation

In this article, we will be discussing one of the vital topics in Rust programming - copying an array. Understanding this concept will help and improve your competence when working with data structures in Rust.

Code snippet for Array Copying in Rust

let original_array = [1, 2, 3, 4, 5];
let copied_array = original_array;
println!("Copied Array : {:?}", copied_array);

Code Explanation for Array Copying in Rust

This is a simple code snippet detailing how to copy an array in Rust. Let’s break down each step to understand better.

First, we declare an array with the let keyword. The original_array stores five integer values.

let original_array = [1, 2, 3, 4, 5];

Then, we are using the let keyword again to declare a new array, copied_array. Instead of initializing it with new values, we are assigning it to our original_array. This way, all the elements of original_array will be copied to copied_array.

let copied_array = original_array;

Finally, we use a println! macro to print our copied_array. The "Copied Array : {:?}", copied_array inside println! is a string literal and Rust format string where{:?} is a placeholder for any type that implements the Debug trait. In this context, it allows us to print each element of the copied_array on the console.

println!("Copied Array : {:?}", copied_array);

As the output of this program, you should see: Copied Array : [1, 2, 3, 4, 5]. And with that, you have successfully copied an array in Rust! Remember, when copying data types in Rust, the source data won’t be usable once it has been copied, because Rust emphasizes giving each value a single owner to manage its lifetime in memory.

rust