Array.copy
Copies the array into a new one
struct Array['Element] {
fun copy(self) -> Array['Element] {}
}
Overview
This function creates a new array with a shallow copy of all the elements. Neither the origin array or the elements are modified.
Copy semantics
The copy of the elements works differently depending on the type of the element. If the element is a Primitive Type, then all the elements are duplicated. All the elements in the new array are new, like in the following example:
var numbers = [2, 4 ,6]
var copied = numbers.copy()
// now we change a number in `copied`
copied[0].add_one()
print(copied[0]) //: 3 -- only the copy changed
print(numbers[0]) //: 2 -- the original stays the same
However, for all other types, the copy will be "shallow". This means that references will be copied, and so, the elements in the new array will point to the same items.
struct Cat { name: String, lives: i64 }
// We create an array of cats
var my_cats = [
Cat { name = "Luna", lives = 9 },
Cat { name = "Loki", lives = 3 },
]
// We create a **shallow** copy
var neighbor_cats = my_cats.copy()
// The cats in `neighbor_cats` are not new, they point to `my_cats`,
// so their data will change in both
neighbor_cats[1].lives -= 1 // Reduce neighbor's Loki's lives by one
print(neighbor_cats[1].lives) //: 2
print(my_cats[1].lives) //: 2 -- the original changed!
See References for more information about this behavior, and for learning how references work in the language.
See Array.clone for creating true, deep clones of the elements,
such that they are not subject to this behavior.