Skip to content

Zig ArrayList

An array in Zig has a fixed length, decided while compiling. But lots of real data doesn’t come in a fixed size: lines in a file, users who sign up, numbers someone types. For that you want a list that grows, and in Zig that’s std.ArrayList. If you know Python’s list, JavaScript’s arrays, Rust’s Vec or C++’s std::vector, it’s the same idea. The one Zig twist: you hand it an allocator every time it might need memory.

Here’s a list of numbers that starts empty and grows:

const std = @import("std");
pub fn main(init: std.process.Init) !void {
const gpa = init.gpa;
var scores: std.ArrayList(u32) = .empty;
defer scores.deinit(gpa);
try scores.append(gpa, 70);
try scores.append(gpa, 85);
try scores.append(gpa, 92);
std.debug.print("{d} scores: {any}\n", .{ scores.items.len, scores.items });
}

Output:

3 scores: { 70, 85, 92 }

Line by line:

  • std.ArrayList(u32) is the type: a list of u32 values. ArrayList is a function that takes a type and returns a struct, the same trick you saw in Zig Generic Data Structures.
  • = .empty starts it with no items and no memory. It doesn’t allocate anything yet.
  • defer scores.deinit(gpa) gives the memory back when main ends. Write it on the very next line, every time.
  • append(gpa, 70) adds an item at the end. It takes the allocator because the list might need more room, and it needs try because getting more room can fail with error.OutOfMemory.
  • scores.items is the list’s contents.

Notice that scores is a var. Appending changes the list, so it can’t be const.

scores.items is an ordinary slice, []u32. Everything you know about slices works on it: indexing, .len, for loops, slicing, passing it to functions.

const std = @import("std");
fn average(nums: []const u32) u32 {
var sum: u32 = 0;
for (nums) |n| sum += n;
return sum / @as(u32, @intCast(nums.len));
}
pub fn main(init: std.process.Init) !void {
const gpa = init.gpa;
var scores: std.ArrayList(u32) = .empty;
defer scores.deinit(gpa);
try scores.appendSlice(gpa, &.{ 70, 85, 92, 61 });
scores.items[3] = 81;
for (scores.items, 0..) |s, i| {
std.debug.print("#{d}: {d}\n", .{ i, s });
}
std.debug.print("average: {d}\n", .{average(scores.items)});
std.debug.print("first two: {any}\n", .{scores.items[0..2]});
}

Output:

#0: 70
#1: 85
#2: 92
#3: 81
average: 82
first two: { 70, 85 }

appendSlice adds several items in one go. &.{ 70, 85, 92, 61 } is a pointer to a small array, which turns into the slice appendSlice wants. Then average takes a plain []const u32 and has no idea the numbers came from an ArrayList. That’s the normal way to write functions: take a slice, not a list, unless the function needs to add or remove items.

Besides adding at the end, you can insert at any position and remove from any position:

const std = @import("std");
pub fn main(init: std.process.Init) !void {
const gpa = init.gpa;
var queue: std.ArrayList([]const u8) = .empty;
defer queue.deinit(gpa);
try queue.appendSlice(gpa, &.{ "Ana", "Bo", "Cy", "Di" });
try queue.insert(gpa, 0, "Eve");
printAll("after insert", queue.items);
const gone = queue.orderedRemove(2);
std.debug.print("orderedRemove took {s}\n", .{gone});
printAll("now", queue.items);
const swapped = queue.swapRemove(0);
std.debug.print("swapRemove took {s}\n", .{swapped});
printAll("now", queue.items);
}
fn printAll(label: []const u8, names: []const []const u8) void {
std.debug.print("{s}:", .{label});
for (names) |n| std.debug.print(" {s}", .{n});
std.debug.print("\n", .{});
}

Output:

after insert: Eve Ana Bo Cy Di
orderedRemove took Bo
now: Eve Ana Cy Di
swapRemove took Eve
now: Di Ana Cy

There are two ways to remove, and the difference matters:

  • orderedRemove(i) keeps the order. Every item after i shifts one place to the left, so on a long list it’s slow (it touches every later item).
  • swapRemove(i) moves the last item into the gap. It’s fast no matter how long the list is, but the order changes: Di jumped to the front.

Use swapRemove when order doesn’t matter (a bag of enemies in a game, a set of open connections) and orderedRemove when it does (a queue, a sorted list). insert has the same cost as orderedRemove, because it shifts items to the right to make a gap.

By the way, printing a list of strings with {any} shows the bytes as numbers, not text, which is why printAll loops and prints each name with {s}.

Taking from the end: pop, last and lastPtr

Section titled “Taking from the end: pop, last and lastPtr”

pop removes the last item and gives it back. On an empty list there’s nothing to give, so it returns an optional: ?T, which is null when the list is empty. That makes a neat loop:

const std = @import("std");
pub fn main(init: std.process.Init) !void {
const gpa = init.gpa;
var stack: std.ArrayList(u8) = .empty;
defer stack.deinit(gpa);
try stack.appendSlice(gpa, "abc");
std.debug.print("top: {?c}\n", .{stack.last()});
if (stack.lastPtr()) |top| top.* = 'C';
while (stack.pop()) |c| {
std.debug.print("popped {c}\n", .{c});
}
std.debug.print("empty now, last is {?c}\n", .{stack.last()});
}

Output:

top: c
popped C
popped b
popped a
empty now, last is null
  • last() gives a copy of the last item, or null (it doesn’t remove anything).
  • lastPtr() gives a pointer to the last item, or null, so you can change it in place.
  • while (stack.pop()) |c| keeps going until pop returns null. You’ll see this “loop until null” shape all over Zig, and Zig Iterators is all about it.

An ArrayList usually has more room than it’s using. items.len is how many items you’ve added; capacity is how many fit before it has to ask the allocator for a bigger block. When it does grow, it asks for extra (about one and a half times as much), so most appends don’t allocate at all.

If you know roughly how many items are coming, you can ask for the room up front:

const std = @import("std");
pub fn main(init: std.process.Init) !void {
const gpa = init.gpa;
var squares: std.ArrayList(u64) = try .initCapacity(gpa, 100);
defer squares.deinit(gpa);
std.debug.print("len {d}, capacity {d}\n", .{ squares.items.len, squares.capacity });
for (0..100) |i| {
squares.appendAssumeCapacity(i * i);
}
std.debug.print("len {d}, capacity {d}\n", .{ squares.items.len, squares.capacity });
std.debug.print("last one: {d}\n", .{squares.last().?});
squares.clearRetainingCapacity();
std.debug.print("len {d}, capacity {d}\n", .{ squares.items.len, squares.capacity });
}

Output:

len 0, capacity 100
len 100, capacity 100
last one: 9801
len 0, capacity 100
  • initCapacity(gpa, 100) makes an empty list with room for exactly 100 items. On a list you already have, try list.ensureTotalCapacity(gpa, n) does the same job (it may round up), and ensureUnusedCapacity(gpa, n) means “room for n more”.
  • appendAssumeCapacity adds without allocating, so it takes no allocator and needs no try. If you’re wrong and there’s no room, a safe build stops with a panic instead of writing past the end.
  • clearRetainingCapacity() empties the list but keeps the memory, handy when you refill the same list in a loop. clearAndFree(gpa) empties it and gives the memory back.

Don’t worry about capacity in everyday code. Plain append is fast. Reserving room is an easy win when you already know the count, like when you’re copying from another list.

Don’t keep pointers into a list that grows

Section titled “Don’t keep pointers into a list that grows”

This is the classic ArrayList bug, and it’s worth slowing down for. When the list runs out of capacity, append gets a new, bigger block of memory, copies the items over and frees the old block. Any pointer or slice you took before that still points at the old block:

const std = @import("std");
pub fn main(init: std.process.Init) !void {
const gpa = init.gpa;
var list: std.ArrayList(u32) = .empty;
defer list.deinit(gpa);
var other: std.ArrayList(u32) = .empty;
defer other.deinit(gpa);
try list.append(gpa, 1);
try other.append(gpa, 7);
const first = &list.items[0]; // points into the current block
for (0..1000) |i| try list.append(gpa, @intCast(i)); // the list moves
std.debug.print("first is {d}\n", .{first.*}); // reads freed memory
}

You’ll see something like:

first is 1431655765

There’s no compile error and no panic: just a wrong number (here the 0x55 bytes a debug build writes over freed memory; in a fast build it’s whatever happens to be there). Sometimes it even prints the right number, because the allocator managed to grow the block in place, which makes the bug harder to catch.

The rules:

  • A pointer or slice into items is only good until the next call that can grow the list: append, appendSlice, insert, ensureTotalCapacity and so on. Any call that takes the allocator can move the items.
  • Store indexes instead of pointers when you need to remember a spot across appends. list.items[i] always finds the item, wherever it lives now.
  • Or reserve the full capacity first. Once there’s room, appends won’t move anything.

The language reference on lifetime and ownership uses this exact example. Zig Lifetimes & Ownership has more on dangling pointers.

Handing the items to someone else: toOwnedSlice

Section titled “Handing the items to someone else: toOwnedSlice”

A function that builds a list often wants to return just the items, as a plain slice. toOwnedSlice does that: it gives you a slice of exactly the right length, and leaves the list empty. The caller now owns the slice and frees it with free:

const std = @import("std");
/// Returns the numbers from 1 to `n` that divide by 3.
/// Caller owns the returned memory.
fn multiplesOfThree(gpa: std.mem.Allocator, n: u32) ![]u32 {
var list: std.ArrayList(u32) = .empty;
errdefer list.deinit(gpa);
var i: u32 = 1;
while (i <= n) : (i += 1) {
if (i % 3 == 0) try list.append(gpa, i);
}
return list.toOwnedSlice(gpa);
}
pub fn main(init: std.process.Init) !void {
const gpa = init.gpa;
const threes = try multiplesOfThree(gpa, 20);
defer gpa.free(threes);
std.debug.print("{any}\n", .{threes});
}

Output:

{ 3, 6, 9, 12, 15, 18 }

Two details make this correct:

  • There’s no defer list.deinit(gpa), because on success the memory leaves the function inside the returned slice. Instead, errdefer list.deinit(gpa) cleans up only if something fails halfway (see Zig Errdefer).
  • main frees the slice with gpa.free, not with deinit. Once you’ve called toOwnedSlice, it’s an ordinary slice from the allocator.

A list of bytes is Zig’s usual “string builder”. Besides append and appendSlice, it has a print method that formats straight into the list:

const std = @import("std");
pub fn main(init: std.process.Init) !void {
const gpa = init.gpa;
const items = [_][]const u8{ "milk", "eggs", "bread" };
var text: std.ArrayList(u8) = .empty;
defer text.deinit(gpa);
try text.appendSlice(gpa, "Shopping list:\n");
for (items, 1..) |item, n| {
try text.print(gpa, " {d}. {s}\n", .{ n, item });
}
try text.append(gpa, '!');
std.debug.print("{s}\n", .{text.items});
}

Output:

Shopping list:
1. milk
2. eggs
3. bread
!

You can’t do this with ++, which only joins strings known while compiling. When you build text at run time and don’t know the final length, an ArrayList(u8) is the tool. Finish with toOwnedSlice if a function needs to return the text.

Start with the array [_]i32{ 4, 7, 10, 3, 8, 1 }. Copy only the even numbers into a new ArrayList(i32) and print the list and how many there are.

Hint: if (@mod(n, 2) == 0) try evens.append(gpa, n);. Don’t forget the defer evens.deinit(gpa); line.

Show solution
const std = @import("std");
pub fn main(init: std.process.Init) !void {
const gpa = init.gpa;
const numbers = [_]i32{ 4, 7, 10, 3, 8, 1 };
var evens: std.ArrayList(i32) = .empty;
defer evens.deinit(gpa);
for (numbers) |n| {
if (@mod(n, 2) == 0) try evens.append(gpa, n);
}
std.debug.print("{d} even: {any}\n", .{ evens.items.len, evens.items });
}

Output:

3 even: { 4, 10, 8 }

@mod is used instead of % because n is a signed number, and Zig wants you to say which kind of remainder you mean for those.

Fill a list with 5, -2, 8, -1, -7, 3, then remove every negative number in place, keeping the order of the rest.

Hint: removing shifts later items left, so if you loop forwards you’ll skip some. Loop with a while and only move to the next index when you didn’t remove anything.

Show solution
const std = @import("std");
pub fn main(init: std.process.Init) !void {
const gpa = init.gpa;
var list: std.ArrayList(i32) = .empty;
defer list.deinit(gpa);
try list.appendSlice(gpa, &.{ 5, -2, 8, -1, -7, 3 });
var i: usize = 0;
while (i < list.items.len) {
if (list.items[i] < 0) {
_ = list.orderedRemove(i);
} else {
i += 1;
}
}
std.debug.print("{any}\n", .{list.items});
}

Output:

{ 5, 8, 3 }

After a removal, the next item slides into index i, so you check i again instead of moving on. orderedRemove returns the removed value; _ = throws it away. Checking list.items.len each time matters too, because the list gets shorter as you go.

Write fn join(gpa: std.mem.Allocator, words: []const []const u8) ![]u8 that returns the words joined with ", ", like "red, green, blue". Use an ArrayList(u8) and toOwnedSlice.

Hint: add ", " before every word except the first one (if (i > 0)).

Show solution
const std = @import("std");
/// Caller owns the returned memory.
fn join(gpa: std.mem.Allocator, words: []const []const u8) ![]u8 {
var out: std.ArrayList(u8) = .empty;
errdefer out.deinit(gpa);
for (words, 0..) |word, i| {
if (i > 0) try out.appendSlice(gpa, ", ");
try out.appendSlice(gpa, word);
}
return out.toOwnedSlice(gpa);
}
pub fn main(init: std.process.Init) !void {
const gpa = init.gpa;
const line = try join(gpa, &.{ "red", "green", "blue" });
defer gpa.free(line);
std.debug.print("{s}\n", .{line});
}

Output:

red, green, blue

errdefer frees the half-built text if an append fails, and toOwnedSlice hands the finished bytes to the caller. (The standard library also has std.mem.join(gpa, ", ", words), which does exactly this.)

  • std.ArrayList(T) is Zig’s growable list. Start it with .empty and free it with defer list.deinit(gpa).
  • Calls that may allocate take the allocator and need try: append, appendSlice, insert, print, toOwnedSlice.
  • list.items is a normal slice. Pass it to functions that take []const T.
  • orderedRemove keeps the order (slow on long lists), swapRemove is fast but moves the last item into the gap. pop, last and lastPtr return optionals.
  • Capacity is the room already reserved. initCapacity and ensureTotalCapacity reserve it up front.
  • Pointers into items break when the list grows. Keep indexes instead.
  • toOwnedSlice turns the list into a slice the caller owns and frees with free.

Next up: Zig HashMap, looking things up by key instead of by position.

Quick check

1. Which line correctly starts an empty list of i32 in Zig 0.17?
2. You need to remove an item and you do not care about order. Which call is fastest on a long list?
3. You saved const p = &list.items[0]; and then appended 500 items. What about p?
4. A function returns list.toOwnedSlice(gpa). How does the caller clean up?