Values and copying
Which Sarlin values are copied, which are shared, and how to request a collection copy.
Value types
Numeric values and booleans are value types. Assignment, function arguments and return values copy them. Changing the copy does not change the original value.
Reference types
Strings, arrays, dictionaries and class instances are managed reference types. Assignment, function arguments and return values share the same value instead of copying its contents. Sarlin keeps the shared value alive for as long as a reference to it exists.
Mutating an array, dictionary or class instance through one reference is therefore visible through its other references:
func main() {
local var first int64[] = [1, 2]
local var second int64[] = first
second[0] = 99
print(first)
}[99, 2]Strings are shared too, but strings are immutable. Operations such asto_upper(), trim() andreplace() return a new string.
Shallow collection copies
duplicate() creates a new outer array or dictionary. Values stored directly in that outer collection are copied. Nested arrays, nested dictionaries and class instances remain shared.
func main() {
local var original int64[][] = [[1], [2]]
local var shallow int64[][] = original.duplicate()
shallow[0][0] = 9
print(original[0][0])
}9Deep collection copies
duplicate_deep() creates a new outer collection and recursively copies nested arrays and dictionaries. Changing a copied nested collection does not change the original:
func main() {
local var original int64[][] = [[1], [2]]
local var deep int64[][] = original.duplicate_deep()
deep[0][0] = 7
print(original[0][0])
}1Constants and fixed collections
A const declaration cannot be reassigned. An array or dictionary declared as a constant also cannot be indexed or resized through its constant name. Because managed values are references, this does not make the underlying value globally immutable: mutation through another variable reference is still visible.
Fixed array and dictionary types prevent their size from changing. Their mutable elements may still be replaced. A constant class reference cannot be reassigned, but the instance'svar fields and methods remain mutable.