Ein generischer Stack von Grund auf
Typparametrisches LIFO über einem Allocator.
Ein generischer Stack von Grund auf ist eine kostenlose Zig Academy-Lektion auf CoddyKit. Dies ist Lektion 1 von 4. Du kannst die komplette Lektion unten kostenlos lesen – dann übst du sie direkt im Browser mit einem integrierten Code-Editor und einem KI-Tutor rund um die Uhr. Sie ist Teil des Zig Academy-Lernpfads, und dein Fortschritt wird über Web und CoddyKit-App synchronisiert. Der Zig Academy-Kurs umfasst insgesamt 4 Lektionen.
Teile dieser Lektion wurden noch nicht übersetzt und werden auf Englisch angezeigt.
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. 🎯
Häufig gestellte Fragen
Ist die Lektion „Ein generischer Stack von Grund auf“ kostenlos?
Ja — der vollständige Text von „Ein generischer Stack von Grund auf“ ist hier im Web kostenlos zu lesen. Um sie interaktiv zu üben (integrierter Code-Editor und 24/7 KI-Tutor) und den Rest des Zig Academy-Kurses freizuschalten, upgrade auf CoddyKit PRO. Der Zig Academy-Kurs umfasst insgesamt 4 Lektionen.
Was lerne ich in „Ein generischer Stack von Grund auf“?
Typparametrisches LIFO über einem Allocator. Du übst Zig Academy mit praktischem Code, den du direkt im Browser ausführst, und ein 24/7 KI-Tutor beantwortet deine Fragen während du die Lektion bearbeitest.
Brauche ich Erfahrung, um Zig Academy zu starten?
Keine Vorkenntnisse erforderlich. Zig Academy auf CoddyKit ist für Anfänger bis fortgeschrittene Lernende strukturiert, sodass du hier starten oder von Anfang an beginnen und in deinem eigenen Tempo voranschreiten kannst. Dies ist Lektion 1 von 4.
Wie lange dauert die Lektion „Ein generischer Stack von Grund auf“?
Die meisten CoddyKit-Lektionen dauern etwa 5–10 Minuten. Jede ist kompakt und interaktiv, sodass du stetig Fortschritte machst und genau dort weitermachst, wo du aufgehört hast – im Web und in der App.
Kann ich in dieser Zig Academy-Lektion Code schreiben und ausführen?
Ja. Jede Zig Academy-Lektion enthält einen integrierten Code-Editor, sodass du echten Code direkt in deinem Browser schreibst und ausführst und sofort KI-Feedback erhältst — ohne lokale Einrichtung erforderlich.
Alle Lektionen in diesem Kurs
- Ein generischer Stack von Grund auf
- Eine einfach verkettete Liste
- HashMap und AutoHashMap verwenden
- Profiling und Sicherheitsabwägungen