Zig Arrays
An array is a fixed number of values of the same type, stored one after another in memory: five scores, seven day names, a 3 × 3 game board. In Zig, the length is part of the array’s type and is decided while compiling, so an array never grows or shrinks. That sounds limiting, but it makes arrays fast, simple and safe, and they’re the base that slices (the type you’ll pass around most) are built on.
Making an array
Section titled “Making an array”You write an array type as [N]T: N items of type T. Put the values in braces after it:
const std = @import("std");
pub fn main() void { var scores = [5]u32{ 70, 85, 92, 60, 77 }; std.debug.print("first: {d}, last: {d}\n", .{ scores[0], scores[4] }); scores[3] = 65; std.debug.print("all: {any}\n", .{scores}); std.debug.print("length: {d}\n", .{scores.len});}Output:
first: 70, last: 77all: { 70, 85, 92, 65, 77 }length: 5[5]u32{ ... }makes an array of fiveu32values.scores[0]is the first item. Like in C, Python and JavaScript, counting starts at 0, so the last of five items isscores[4].scores[3] = 65;changes one item. That needs avar; the items of aconstarray can’t change..lenis the number of items.{any}prints the whole array.
Counting the items yourself is boring and easy to get wrong. Write _ instead of the number, and Zig counts them for you:
const std = @import("std");
pub fn main() void { const primes = [_]u8{ 2, 3, 5, 7, 11 }; std.debug.print("{} with {d} items\n", .{ @TypeOf(primes), primes.len });}Output:
[5]u8 with 5 itemsThe type is still [5]u8; _ just means “count them”. This is the form you’ll write most. If you do give a number, it has to match: [3]u8{ 1, 2 } fails with expected 3 array elements; found 2.
Staying inside the array
Section titled “Staying inside the array”If Zig can see while compiling that an index is too big, it stops the build:
pub fn main() void { const a = [3]u8{ 1, 2, 3 }; _ = a[3];}main.zig:3:11: error: index 3 outside array of length 3 _ = a[3]; ^When the index is only known while running, Zig checks it then. Here’s the classic off-by-one mistake, using <= instead of <:
const std = @import("std");
pub fn main() void { const days = [_][]const u8{ "Mon", "Tue", "Wed" }; var i: usize = 0; while (i <= days.len) : (i += 1) { std.debug.print("{s}\n", .{days[i]}); }}You’ll see something like:
MonTueWedthread 22200 panic: index out of bounds: index 3, len 3main.zig:7:40: 0x11e3e16 in main (main.zig) std.debug.print("{s}\n", .{days[i]}); ^In C this would quietly read whatever memory comes after the array. Zig stops the program and tells you the index, the length and the line. These checks are on in debug and safe builds; in fast and small builds they’re left out for speed, so test in debug mode. [_][]const u8 here is an array of strings, by the way: each item is a []const u8.
Looping over an array
Section titled “Looping over an array”You already know for from Zig For. It works directly on arrays, and you can count along with 0.. (or 1.. to start at 1):
const std = @import("std");
pub fn main() void { const weekdays = [_][]const u8{ "Mon", "Tue", "Wed", "Thu", "Fri" }; const weekend = [_][]const u8{ "Sat", "Sun" }; const week = weekdays ++ weekend; std.debug.print("{d} days\n", .{week.len}); for (week, 1..) |day, n| { std.debug.print("{d}. {s}\n", .{ n, day }); }}Output:
7 days1. Mon2. Tue3. Wed4. Thu5. Fri6. Sat7. Sun++ joined the two arrays into one array of 7 items; more on that below. To change the items in a loop, loop over &array and capture a pointer with |*item|, as you’ll see in the next section.
Filling an array
Section titled “Filling an array”To make an array where every item has the same value, use @splat. To fill it in a loop instead, start with undefined (meaning “no value yet”) and set every item before you read it:
const std = @import("std");
pub fn main() void { var zeros: [5]u8 = @splat(0); const sevens: [3]i32 = @splat(7); zeros[1] = 4; std.debug.print("{any}\n{any}\n", .{ zeros, sevens });
var squares: [6]u32 = undefined; for (&squares, 0..) |*sq, i| { sq.* = @intCast(i * i); } std.debug.print("{any}\n", .{squares});}Output:
{ 0, 4, 0, 0, 0 }{ 7, 7, 7 }{ 0, 1, 4, 9, 16, 25 }@splat(0) copies one value into every slot. It needs to know the array type, so write the type on the variable: var zeros: [5]u8 = @splat(0);. In the loop, &squares and |*sq| give you a pointer to each item, and sq.* = ... writes through it (pointers come in Zig Pointers). @intCast turns the usize index into a u32.
Joining arrays with ++
Section titled “Joining arrays with ++”++ puts two arrays end to end and gives you a new, longer array. Both lengths have to be known while compiling, which is always true for arrays, so the values themselves can come from anywhere:
const std = @import("std");
pub fn main() void { var first = [_]u8{ 1, 2, 3 }; first[0] = 10; const both = first ++ [_]u8{ 4, 5 }; std.debug.print("{any}\n", .{both});}Output:
{ 10, 2, 3, 4, 5 }The result has the type [5]u8, worked out while compiling. What ++ can’t do is join two things whose length is only known while running, like a slice of text the user typed. For that you need a buffer or an allocator; you saw std.mem.print for text in Zig Strings.
The length must be known while compiling
Section titled “The length must be known while compiling”Since the length is part of the type, you can’t make an array from a length that’s only known at run time:
const std = @import("std");
pub fn main() void { var n: usize = 5; n += 1; var buf: [n]u8 = undefined; _ = &buf;}main.zig:6:15: error: unable to resolve comptime value var buf: [n]u8 = undefined; ^main.zig:6:15: note: types must be comptime-knownWhen you don’t know the size in advance, you have two choices: make an array big enough for the worst case and use part of it (with a slice), or ask an allocator for memory, or use an ArrayList, which grows as needed.
Arrays are values
Section titled “Arrays are values”This surprises people coming from JavaScript, Python or Java: in Zig, an array is a value, like a number. Assigning it to another variable copies all the items:
const std = @import("std");
pub fn main() void { const a = [_]u8{ 1, 2, 3 }; var b = a; b[0] = 99; std.debug.print("a: {any}\nb: {any}\n", .{ a, b }); std.debug.print("equal: {}\n", .{std.mem.eql(u8, &a, &b)}); const c = [_]u8{ 1, 2, 3 }; std.debug.print("a == c: {}\n", .{std.mem.eql(u8, &a, &c)});}Output:
a: { 1, 2, 3 }b: { 99, 2, 3 }equal: falsea == c: trueChanging b didn’t touch a. The same goes for passing an array to a function: the function gets a copy, as you saw in Zig Function Parameters. To compare two arrays, use std.mem.eql with & in front of each. == doesn’t work on arrays: you get operator == not allowed for type '[3]u8'.
Arrays of arrays
Section titled “Arrays of arrays”An array’s items can be arrays too. [3][4]u8 is “3 rows, each an array of 4 u8”:
const std = @import("std");
pub fn main() void { var grid = [3][4]u8{ .{ 1, 2, 3, 4 }, .{ 5, 6, 7, 8 }, .{ 9, 10, 11, 12 }, }; grid[1][2] = 0; for (grid) |row| { for (row) |cell| { std.debug.print("{d:>3}", .{cell}); } std.debug.print("\n", .{}); } std.debug.print("rows: {d}, columns: {d}\n", .{ grid.len, grid[0].len });}Output:
1 2 3 4 5 6 0 8 9 10 11 12rows: 3, columns: 4grid[1][2] is row 1, column 2 (both counting from 0). Inside the outer braces, each row is written .{ ... }: Zig already knows each row is a [4]u8, so you don’t have to repeat the type. {d:>3} prints each number right-aligned in 3 spaces, so the columns line up. The reference on multidimensional arrays has more.
Unpacking an array
Section titled “Unpacking an array”When an array holds a few values with different meanings, you can unpack it into separate names in one line:
const std = @import("std");
pub fn main() void { const rgb = [_]u8{ 255, 128, 0 }; const red, const green, const blue = rgb; std.debug.print("r={d} g={d} b={d}\n", .{ red, green, blue });}Output:
r=255 g=128 b=0The number of names must match the array’s length. It’s the same syntax you used to unpack a tuple in Zig Functions.
Practice
Section titled “Practice”1. Average temperature
Section titled “1. Average temperature”Make an array of seven daily temperatures (i32) and print their sum and their average.
Hint: add them up in a for loop. To divide, @divTrunc(sum, @as(i32, temps.len)) works because temps.len is known while compiling.
Show solution
const std = @import("std");
pub fn main() void { const temps = [_]i32{ 12, 15, 9, 20, 18, 11, 13 }; var sum: i32 = 0; for (temps) |t| sum += t; const avg = @divTrunc(sum, @as(i32, temps.len)); std.debug.print("sum: {d}, average: {d}\n", .{ sum, avg });}Output:
sum: 98, average: 14@divTrunc is division that drops the remainder; Zig makes you pick a rounding style when dividing signed numbers. @as(i32, temps.len) works without a cast because 7 fits in an i32 and Zig knows it at compile time.
2. Reverse into a new array
Section titled “2. Reverse into a new array”Given const word = [_]u8{ 'z', 'i', 'g', 'g', 'y' };, build a second array with the letters in reverse order and print both with {s}.
Hint: make var reversed: [word.len]u8 = undefined; and loop over word with an index. Item i goes to position word.len - 1 - i.
Show solution
const std = @import("std");
pub fn main() void { const word = [_]u8{ 'z', 'i', 'g', 'g', 'y' }; var reversed: [word.len]u8 = undefined; for (word, 0..) |letter, i| { reversed[word.len - 1 - i] = letter; } std.debug.print("{s} -> {s}\n", .{ word, reversed });}Output:
ziggy -> yggiz[word.len]u8 is allowed because word.len is known while compiling. An array of u8 can be printed as text with {s}.
3. Tic-tac-toe board
Section titled “3. Tic-tac-toe board”Make a 3 × 3 board of u8, filled with '.'. Put an 'X' in the middle and an 'O' in the top-right corner, then print the board, one row per line.
Hint: var board: [3][3]u8 = @splat(@splat('.')); fills every row. Each row is a [3]u8, so you can print it with {s}.
Show solution
const std = @import("std");
pub fn main() void { var board: [3][3]u8 = @splat(@splat('.')); board[1][1] = 'X'; board[0][2] = 'O'; for (board) |row| { std.debug.print("{s}\n", .{row}); }}Output:
..O.X....The inner @splat('.') makes one row, and the outer @splat copies that row three times.
- An array type is
[N]T: exactlyNitems of typeT. Write[_]T{ ... }to let Zig count. - Items are numbered from 0;
.lenis the length. Bad indexes are caught while compiling when possible, otherwise with a panic in safe builds. - Fill an array with
@splat(value). The old**operator was removed in Zig 0.17. ++joins arrays into a new, longer array.- The length must be known while compiling. For sizes you only know at run time, use slices, allocators or an ArrayList.
- Arrays are values: assigning copies them. Compare them with
std.mem.eql, not==. [rows][cols]Tmakes a grid;grid[r][c]picks one cell.
Next up: Zig Pointers, how to point at a value instead of copying it, with *T, &x and ptr.*.
Quick check
Section titled “Quick check”Quick check
Read more
Section titled “Read more”- Zig language reference: Arrays: array literals,
++,@splatand more examples. - Zig language reference: Multidimensional Arrays: grids and nested loops.
- Zig language reference: Destructuring Arrays: unpacking an array into several names.
- Zig 0.17.0 release notes: Array Multiplication Syntax Removed: why
**went away and how to update old code.