Zig Arrays
An array is a fixed-size group of values that all share one type. Zig stores the values in order, and each value sits at a numbered position called an index.
An array holds three numbers
This array stores three i32 values. The printout shows the values and the counted length.
const std = @import("std");
pub fn main() !void {
const out = std.io.getStdOut().writer();
const nums = [_]i32{ 3, 1, 4 };
try out.print("{any}\n", .{nums});
try out.print("{d}\n", .{nums.len});
}
Index 1 changes from 1 to 9
Indexes start at 0. Writing at index 1 replaces the second value.
const std = @import("std");
pub fn main() !void {
const out = std.io.getStdOut().writer();
var nums = [_]i32{ 3, 1, 4 };
nums[1] = 9;
try out.print("{d}\n", .{nums[1]});
try out.print("{any}\n", .{nums});
}
A loop adds every value
A for loop visits the values in order. The total proves all three values were added.
const std = @import("std");
pub fn main() !void {
const out = std.io.getStdOut().writer();
const nums = [_]i32{ 3, 1, 4 };
var total: i32 = 0;
for (nums) |n| {
total += n;
}
try out.print("{d}\n", .{total});
}
Example
const std = @import("std");
pub fn main() !void {
const out = std.io.getStdOut().writer();
const scores = [_]i32{ 10, 20, 30, 40 };
var total: i32 = 0;
for (scores) |score| {
total += score;
}
try out.print("{d}\n", .{scores[0]});
try out.print("{d}\n", .{scores.len});
try out.print("{d}\n", .{total});
}
Key points
- Array literal: square brackets and curly braces list the values, as in [_]i32{ 3, 1, 4 }.
- Inferred length: the underscore in [_] tells Zig to count the values and fix the length.
- Length: .len gives the number of values stored in the array.
- Index: indexes start at 0, so nums[0] reads the first value.
- Change: an array declared with var lets you assign a new value at an index.
- Loop: a for loop visits each value in the array in order.
In this example, scores holds four i32 values. The for loop adds each score into total. The printouts then show the first score at index 0, the length 4, and the added total 100.
Note
an array length cannot grow or shrink after the array is created.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
What does nums[0] give for const nums = [_]i32{ 7, 8, 9 };?