ゼロから作る汎用スタック
Allocator上に構築する型パラメーター付きLIFOです
「ゼロから作る汎用スタック」はCoddyKit上の無料Zig Academyレッスンです。 これはレッスン1/4です。 下記で完全なレッスンを無料で読むことができます。その後、ブラウザ内の組み込みコードエディタと24時間対応のAIチューターでハンズオン演習できます。 これはZig Academy学習パスの一部であり、ウェブとCoddyKitアプリ全体で進捗が同期されます。 Zig Academyコースには全4レッスンが含まれています。
このレッスンの一部はまだ翻訳されておらず、英語で表示されています。
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. 🎯
よくある質問
「ゼロから作る汎用スタック」レッスンは無料ですか?
はい。「ゼロから作る汎用スタック」の完全なテキストはこのウェブで無料で読めます。インタラクティブに演習し(組み込みコードエディタと24時間対応のAIチューター)、Zig Academyコースの残りをアンロックするには、CoddyKit PROにアップグレードしてください。 Zig Academyコースには全4レッスンが含まれています。
「ゼロから作る汎用スタック」で何を学びますか?
Allocator上に構築する型パラメーター付きLIFOです ブラウザで直接実行するハンズオンコードでZig Academyを演習し、24時間対応のAIチューターがレッスンを進める中での質問に答えます。
Zig Academyを始めるのに経験は必要ですか?
事前経験は必要ありません。CoddyKitのZig Academyは初級者から上級者向けに構成されているため、ここから始めるか最初から始めて、自分のペースで進むことができます。 これはレッスン1/4です。
「ゼロから作る汎用スタック」レッスンにはどのくらい時間がかかりますか?
ほとんどのCoddyKitレッスンは約5~10分かかります。各レッスンはコンパクトでインタラクティブなので、着実に進歩し、ウェブとアプリ全体で正確に前回の場所から再開できます。
このZig Academyレッスンでコードを書いて実行できますか?
はい。すべてのZig Academyレッスンに組み込みコードエディタが含まれているため、ブラウザでリアルコードを書いて実行し、即座のAIフィードバックを取得できます。ローカル設定は不要です。