July 26, 2025In this post I will make the case for the concept of a “runtime resizable struct” in Zig. I will then design an API by exploiting Zig’s powerful comptime functionality.If you want to skip straight to the implementation, a minimal proof of concept is available as a package on GitHub.Zig has support for many kinds of collection types in its standard library. All of them can broadly be broken down to two primitive backing types for contiguous data storage:[N]T – arrays, when you always know the length at compile time.[*]T – many-item pointers, when you may not know the length at compile time.You may be wondering about slices. Slices can be thought of as syntax sugar around a many-item pointer and a length:// A desugared slice type const PersonSlice = struct { ptr: [*]Person, len: usize, }; Once you allocate the slice, you can’t grow or shrink its memory without reallocating. That’s why we have std.ArrayList, which is just a wrapper around a slice (itself sugar for many-item pointers) that provides helpers to manage reallocating that slice:// A naive ArrayList implementation const PersonList = struct { items: []Person, pub fn append(self: PersonArrayList, allocator: Allocator, person: Person) !void { self.items = try allocator.realloc(self.items, self.items.len + 1); self.items[self.items.len] = pie; } }; We can build up lots of interesting collection types with these primitives, but at the end of the day, we have arrays, many-item pointers, and slices (which are just many-item pointers!). If the size is fixed at compile time, you’ll probably be working with arrays. If the size may be influenced by runtime values, you’ll probably be working with many-item pointers.Arrays/pointers work well for contiguous storage of the same type, but a struct can be thought of as contiguous collection of different types:const City = struct { name: []const u8, population: u32, area: f32, }; It has a compile time known number of values, they have a compile time known size, an...
First seen: 2025-07-26 22:15
Last seen: 2025-07-27 05:20