A Generic Stack from Scratch
Type-parametric LIFO over an allocator.
A Generic Stack from Scratch is a free Zig Academy lesson on CoddyKit — lesson 1 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Zig Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
What a Stack Does
A stack is a LIFO collection: the last item you push is the first one you pop. Think of plates piled on a counter. 🍽️
Make It Generic
To hold any element type, write a function that takes a type and returns a struct type. Each call gives a stack tailored to that type.
fn Stack(comptime T: type) type {
return struct {};
}Store Items and an Allocator
Inside, the struct keeps a growable slice of items plus the allocator it borrows memory from. Zig never hides allocation.
return struct {
items: []T,
len: usize,
alloc: std.mem.Allocator,
};Refer to the Struct with @This
The returned struct is anonymous, so methods name their own type with @This(). That keeps every method fully generic.
const Self = @This();Initialize an Empty Stack
An init function takes the allocator and returns a fresh, empty stack. Nothing is allocated until you push.
fn init(a: std.mem.Allocator) Self {
return .{ .items = &.{}, .len = 0, .alloc = a };
}Push Can Fail
Growing the buffer may need memory, so push returns an error union. Callers handle the out-of-memory case explicitly.
fn push(self: *Self, value: T) !void {
// grow then store
}Reuse realloc to Grow
To make room, ask the allocator to realloc the slice to a larger size. The new length is up to your growth policy.
self.items = try self.alloc.realloc(self.items, self.len + 1);
self.items[self.len] = value;
self.len += 1;Pop the Top Value
pop returns an optional: the top item if the stack has one, or null when it is empty. No crashes on an empty stack.
fn pop(self: *Self) ?T {
if (self.len == 0) return null;
self.len -= 1;
return self.items[self.len];
}Free What You Allocated
Because you own the buffer, you must give it back. A deinit method frees the slice through the same allocator.
fn deinit(self: *Self) void {
self.alloc.free(self.items);
}Use It
Build a concrete type by calling the function, then init it. Stack(i32) is a real, fully checked type ready to push integers.
var s = Stack(i32).init(allocator);
defer s.deinit();
try s.push(42);One Definition, Many Stacks
Call the function with different types and each is a separate, specialized stack. Stack(u8) and Stack(f64) share no code accidentally.
Quick Check
Your generic stack needs heap memory to grow. Where does that memory come from?
Recap
A generic stack is a type-returning function holding items plus an allocator. Push grows, pop returns an optional, and deinit frees. 🎯
Frequently asked questions
Is the “A Generic Stack from Scratch” lesson free?
Yes — the full text of “A Generic Stack from Scratch” is free to read here on the web, and the Zig Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Zig Academy course, upgrade to CoddyKit PRO.
What will I learn in “A Generic Stack from Scratch”?
Type-parametric LIFO over an allocator. You practise Zig Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start Zig Academy?
No prior experience is required. Zig Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 1 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “A Generic Stack from Scratch” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this Zig Academy lesson?
Yes. Every Zig Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- A Generic Stack from Scratch
- A Singly Linked List
- Using HashMap and AutoHashMap
- Profiling and Safety Trade-offs