Una pila genérica desde cero
Una estructura LIFO parametrizada por tipo sobre un asignador.
Una pila genérica desde cero es una lección gratuita de Zig Academy en CoddyKit. Esta es la lección 1 de 4. Puedes leer la lección completa abajo gratuitamente — luego la practicas en el navegador con un editor de código integrado y un tutor de IA 24/7. Forma parte de la ruta de aprendizaje de Zig Academy, y tu progreso se sincroniza en la web y la app de CoddyKit. El curso de Zig Academy incluye 4 lecciones en total.
Partes de esta lección aún no han sido traducidas y se muestran en inglés.
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. 🎯
Preguntas frecuentes
¿La lección «Una pila genérica desde cero» es gratis?
Sí — el texto completo de «Una pila genérica desde cero» es gratis para leer aquí en la web. Para practicarla de forma interactiva (editor de código integrado y tutor de IA 24/7) y desbloquear el resto del curso de Zig Academy, actualiza a CoddyKit PRO. El curso de Zig Academy incluye 4 lecciones en total.
¿Qué aprenderé en «Una pila genérica desde cero»?
Una estructura LIFO parametrizada por tipo sobre un asignador. Practicas Zig Academy con código real que ejecutas directamente en el navegador, y un tutor de IA 24/7 responde tus preguntas mientras trabajas en la lección.
¿Necesito experiencia previa para empezar Zig Academy?
No se requiere experiencia previa. Zig Academy en CoddyKit está estructurado para principiantes hasta estudiantes avanzados, así que puedes empezar aquí o desde el inicio y avanzar a tu ritmo. Esta es la lección 1 de 4.
¿Cuánto tiempo toma la lección «Una pila genérica desde cero»?
La mayoría de las lecciones de CoddyKit toman alrededor de 5–10 minutos. Cada una es compacta e interactiva, así que avanzas constantemente y retomas exactamente por donde dejaste en la web y la app.
¿Puedo escribir y ejecutar código en esta lección de Zig Academy?
Sí. Cada lección de Zig Academy incluye un editor de código integrado, así que escribes y ejecutas código real directamente en tu navegador y obtienes retroalimentación instantánea de IA — sin configuración local necesaria.
Todas las lecciones de este curso
- Una pila genérica desde cero
- Una lista enlazada simple
- Usar HashMap y AutoHashMap
- Perfilado y compromisos de seguridad