複数のdeferの実行順序
遅延コードが逆順に実行される理由を学びます。
「複数のdeferの実行順序」はCoddyKit上の無料Zig Academyレッスンです。 これはレッスン2/4です。 下記で完全なレッスンを無料で読むことができます。その後、ブラウザ内の組み込みコードエディタと24時間対応のAIチューターでハンズオン演習できます。 これはZig Academy学習パスの一部であり、ウェブとCoddyKitアプリ全体で進捗が同期されます。 Zig Academyコースには全4レッスンが含まれています。
このレッスンの一部はまだ翻訳されておらず、英語で表示されています。
More Than One defer
A single scope can hold several defer statements. When the scope ends, Zig has to decide what order to run them in.
They Run in Reverse
Multiple defers fire in reverse order: the last one you wrote runs first, and the first one you wrote runs last.
defer one();
defer two();Last In, First Out
This is classic LIFO behavior, just like a stack. Each defer is pushed on, and unwinding pops them off in reverse.
A Tiny Example
Here two defers run after work. The output is two then one, because the later defer unwinds before the earlier one.
defer print("one");
defer print("two");
work();Why Reverse Makes Sense
Resources usually depend on earlier ones. Reverse order means you release the newest first, so nothing is freed while still in use.
Mirroring Acquisition
Open A, then open B. Reverse defers close B, then A, perfectly mirroring how you set them up.
a.open(); defer a.close();
b.open(); defer b.close();Captured at Schedule Time
Each defer remembers its code in order, even though execution waits. The order is fixed the moment each defer is reached.
Skipped if Never Reached
If the scope exits before a defer line is reached, that defer was never scheduled, so it does not run at all.
if (early) return;
defer late();Per-Scope Stacks
Each scope keeps its own defer stack. Inner scopes unwind their defers before the outer scope unwinds its own.
Predictable Teardown
Knowing the reverse rule lets you reason about cleanup precisely, so your teardown sequence is never a surprise.
A Handy Mental Model
Picture stacking plates: you add them top down, but you must remove from the top, taking the last one off first.
Quick Check
Two defers, one then two. What is the run order?
Recap
Multiple defers unwind in reverse order, like a stack, so the newest resource is released first and cleanup mirrors setup. 🔁
よくある質問
「複数のdeferの実行順序」レッスンは無料ですか?
はい。「複数のdeferの実行順序」の完全なテキストはこのウェブで無料で読めます。インタラクティブに演習し(組み込みコードエディタと24時間対応のAIチューター)、Zig Academyコースの残りをアンロックするには、CoddyKit PROにアップグレードしてください。 Zig Academyコースには全4レッスンが含まれています。
「複数のdeferの実行順序」で何を学びますか?
遅延コードが逆順に実行される理由を学びます。 ブラウザで直接実行するハンズオンコードでZig Academyを演習し、24時間対応のAIチューターがレッスンを進める中での質問に答えます。
Zig Academyを始めるのに経験は必要ですか?
事前経験は必要ありません。CoddyKitのZig Academyは初級者から上級者向けに構成されているため、ここから始めるか最初から始めて、自分のペースで進むことができます。 これはレッスン2/4です。
「複数のdeferの実行順序」レッスンにはどのくらい時間がかかりますか?
ほとんどのCoddyKitレッスンは約5~10分かかります。各レッスンはコンパクトでインタラクティブなので、着実に進歩し、ウェブとアプリ全体で正確に前回の場所から再開できます。
このZig Academyレッスンでコードを書いて実行できますか?
はい。すべてのZig Academyレッスンに組み込みコードエディタが含まれているため、ブラウザでリアルコードを書いて実行し、即座のAIフィードバックを取得できます。ローカル設定は不要です。
このコースのすべてのレッスン
- deferが保証すること
- 複数のdeferの実行順序
- 実践で学ぶdeferとerrdeferの違い
- openとcloseを組み合わせる