Mutable Arrays
Mutable arrays are a sequence of ordered mutable values of a certain type. To define a mutable array, we use the var
keyword inside the array.
let letters = [var "a", "b", "c"];
let a : Text = letters[0];
We declared an immutable variable named letters
and assigned an array value to it. Our array has the keyword var
inside of it after the first bracket to indicate that the values are mutable. The var
keyword is used only once at the beginning.
Notice, that array indexing works the same as for a immutable array.
We could be more explicit about the type of our variable by annotating it:
let letters : [var Text] = [var "a", "b", "c"];
Our mutable array is of type [var Text]
. We could now mutate the values inside the array, as long as we assign new values of type Text
.
letters[0] := "hello";
We can mutate values as many times as we like. Lets change the last value of our array:
let size = letters.size();
letters[size - 1] := "last element";
We used the .size()
method to obtain a Nat
and used that to index into the array, thereby accessing the last element of the array and giving it a new Text
value. The last element is size - 1
because array indexing starts at 0 and the .size()
method counts the size of the array starting at 1.
Our array has now the following value:
[var "hello", "b", "last element"]
Mutable arrays and mutable variables
We could also assign a mutable array to a mutable variable.
var numbers : [var Nat] = [var 8, 8, 3, 0];
numbers[2] := 10; // mutate the value inside the array
numbers := [var 1]; // mutate the value of the variable
numbers := [var]; // mutate the value of the variable
We declared a mutable variable named numbers
. We annotated the type of the variable with [var Nat]
indicating that the value of this variable is a mutable array of Nat
values. We then assigned a mutable array to the variable name. The array has the keyword var
inside of it.
In the second line we access the third element by indexing and mutate the Nat
value at that index.
In the third line, we mutate the value of the variable, which is a whole new mutable array with one single value.
In the last line, we mutate the value of the variable again, which is a whole new mutable array with zero values.
We could mutate the variable again, but the new value has to be of type [var Nat]