To copy an array in Rust, you can use the clone() method or create a new array and copy the elements manually.
In this example,
arr1
with elements.clone()
method to create a copy of arr1
into arr2
.clone()
method creates a deep copy of the array.fn main() {
let arr1 = [1, 2, 3, 4, 5];
let arr2 = arr1.clone();
println!("Array 1: {:?}", arr1);
println!("Array 2 (copy of Array 1): {:?}", arr2);
}
Array 1: [1, 2, 3, 4, 5] Array 2 (copy of Array 1): [1, 2, 3, 4, 5]
In this example,
arr1
with elements.arr2
with the same length as arr1
.arr1
to arr2
individually.fn main() {
let arr1 = [1, 2, 3, 4, 5];
let mut arr2 = [0; 5];
for (i, &val) in arr1.iter().enumerate() {
arr2[i] = val;
}
println!("Array 1: {:?}", arr1);
println!("Array 2 (copy of Array 1): {:?}", arr2);
}
Array 1: [1, 2, 3, 4, 5] Array 2 (copy of Array 1): [1, 2, 3, 4, 5]
In this tutorial, we learned How to Copy an Array in Rust language with well detailed examples.