ArrayList in Zig
The growable list is unmanaged: every append hands the allocator in explicitly.
const std = @import("std");
pub fn main() !void {
var gpa = std.heap.DebugAllocator(.{}){};
defer _ = gpa.deinit();
const alloc = gpa.allocator();
// ArrayList is unmanaged: every growing call takes the allocator.
var hauls = std.ArrayList(f32).empty;
defer hauls.deinit(alloc);
try hauls.append(alloc, 12.5);
try hauls.append(alloc, 8.0);
try hauls.appendSlice(alloc, &.{ 15.25, 6.75 });
std.debug.print("{d} hauls logged\n", .{hauls.items.len});
const last = hauls.items[hauls.items.len - 1];
std.debug.print("first {d:.2}, last {d:.2}\n", .{ hauls.items[0], last });
}
How it works
std.ArrayList(f32).emptystarts with no storage at all.appendandappendSlicetakeallocbecause growing might allocate..itemsis the live slice: index it, measure it, read it back.
Keywords and builtins used here
constdeferf32fnpubtryvarvoid
The run, in numbers
- Lines
- 19
- Characters to type
- 575
- Tokens
- 171
- Three-star pace
- 65 tpm
At the three-star pace of 65 tokens a minute, this run takes about 158 seconds.
Step 2 of 3 in Memory, step 20 of 27 in Language basics.