Mutable arrays
So far, we've worked with immutable arrays, once declared, they can't be changed. Working with constants (immutable data) has its benefits, but sometimes you'll need to use data that can change during the program's execution.
In the following example, we declare the array a_nums as a variable so we can modify its elements even after it's been created:
array_mutable.zig |
|
const std = @import("std"); const print = std.debug.print; pub fn main() void { var a_nums = [_]u16{ 8, 5, 10, 6, 12 }; print("a_nums is:\n\t {any}\n", .{a_nums}); // we increment the first element by 1 a_nums[0] = a_nums[0] + 1; // we change the fourth element (index 3) a_nums[3] = 0; print("After the change, a_nums is: \n\t {any}\n", .{a_nums}); } |
|
$ zig run array_mutable.zig |
|
a_nums is: { 8, 5, 10, 6, 12 } After the change, a_nums is: { 9, 5, 10, 0, 12 } |
We modified the value of two elements in the array:
- The first element was incremented by 1,
- The fourth element was set to 0.
To illustrate the changes we made, here's a step-by-step diagram:
a_nums when declared:
fig. declared array |
After the first change:
fig. Array changed |
After the second change:
fig. Array second change |
In the earlier examples, we declared arrays as constants, their values couldn’t be modified. In this case, a_nums is a mutable array: we can change its values. But... can we add one more value after the last index (4)?
Like this, for example:
|
a_nums[5] = 11; |
|
error: index 5 outside array of length 5 a_nums[5] = 11; |
No. No you can’t add values to an array. The number of elements in an array is fixed, whether it’s constant or variable. The only thing you can change in a mutable array is the values of the existing elements, not its length.
Later on, we'll see that Zig has dynamic structures called ArrayList, which do allow changing the length of the structure. Arrays, however, are very useful and efficient for storing fixed-length data sequences.
Examples of data that are ideal to store in an array
- Days of the week: always 7
- RGB colors: those are 3 u8 values representing the Red, Green, and Blue components of a pixel
- Typical security PIN: 4 digits
- 2D point: 2 values, (x, y)
- 3D point: 3 values, (x, y, z)
- Measurement file: if each row always contains a fixed number of columns (e.g. 4 sensors per row)
You’ll find plenty more examples if you think about it.