Wrote my first data structure using comptime to replace an ArrayList where the maximum size is known at compile time. As I use it as a stack, it only implements append and pop as that is all I need.

#zig #dev

pub fn ConstStack(comptime T: type, size: comptime_int) type { return struct { items: [size]T = undefined, len: usize = 0, const Self = @This(); pub fn append(self: *Self, item: T) !void { if (self.len == size) { return error.OutOfMemory; } self.items[self.len] = item; self.len += 1; } pub fn pop(self: *Self) ?T { if (self.len == 0) return null; self.len -= 1; return self.items[self.len]; } }; }
@h4kor If you don’t know of it, BoundedArray in the standard library may suit your needs. If you do know of it and just want this simpler API, then carry on.

https://mastodon.social/@chazh/114371674461039313

Thanks :) wasn't aware of that. For now my implementation is all I need, but will keep this in mind for the next time.

@h4kor I learned about it right after I built one of these. :)