オプショナル型を宣言する
?を付けて値がない状態を許可します。
「オプショナル型を宣言する」はCoddyKit上の無料Zig Academyレッスンです。 これはレッスン1/4です。 下記で完全なレッスンを無料で読むことができます。その後、ブラウザ内の組み込みコードエディタと24時間対応のAIチューターでハンズオン演習できます。 これはZig Academy学習パスの一部であり、ウェブとCoddyKitアプリ全体で進捗が同期されます。 Zig Academyコースには全4レッスンが含まれています。
このレッスンの一部はまだ翻訳されておらず、英語で表示されています。
Sometimes There Is Nothing
Real programs hit cases where a value is simply absent: a lookup misses, a field is empty. Zig models this absence safely and on purpose.
The Optional Type
An optional type can hold either a real value of some type, or the special value null meaning nothing is there.
Add a Leading Question Mark
You make any type optional by writing ? in front of it. So ?i32 is an integer that might also be null.
var age: ?i32 = null;A Value Fits Right In
An optional happily holds a normal value too. You assign 42 to an ?i32 exactly as you would assign to a plain i32.
var age: ?i32 = 42;null Is the Empty State
The keyword null is the literal that means there is no value. Only optional types are allowed to hold it.
const missing: ?u8 = null;Non-Optionals Reject null
A plain i32 can never be null. The compiler stops you, so absence stays visible in the type rather than hiding as a bad value.
var n: i32 = null; // error: expected i32Wrap Any Type You Like
Optionals are not just for numbers. You can mark a bool, a struct, a slice, or any type as optional by adding the question mark.
var found: ?bool = null;Inference Still Works
Assign an optional value and Zig infers the optional type for you, so you do not always have to spell it out by hand.
const score: ?u32 = 10;Why Not Use a Sentinel
In C people fake absence with values like -1 or a null pointer. Zig gives you a real optional so absence cannot be confused with data.
Absence Is Part of the Type
Because ? lives in the type itself, anyone reading your code instantly sees that a value might be missing and must be handled.
Defaulting to null
It is common to start an optional at null and fill it in later once you actually have the value to store.
var result: ?[]const u8 = null;Quick Check
How do you declare a u32 that might be missing?
Recap
You met optionals: write ? before a type to allow a real value or null. Absence now lives in the type, plain and visible. ❓
よくある質問
「オプショナル型を宣言する」レッスンは無料ですか?
はい。「オプショナル型を宣言する」の完全なテキストはこのウェブで無料で読めます。インタラクティブに演習し(組み込みコードエディタと24時間対応のAIチューター)、Zig Academyコースの残りをアンロックするには、CoddyKit PROにアップグレードしてください。 Zig Academyコースには全4レッスンが含まれています。
「オプショナル型を宣言する」で何を学びますか?
?を付けて値がない状態を許可します。 ブラウザで直接実行するハンズオンコードでZig Academyを演習し、24時間対応のAIチューターがレッスンを進める中での質問に答えます。
Zig Academyを始めるのに経験は必要ですか?
事前経験は必要ありません。CoddyKitのZig Academyは初級者から上級者向けに構成されているため、ここから始めるか最初から始めて、自分のペースで進むことができます。 これはレッスン1/4です。
「オプショナル型を宣言する」レッスンにはどのくらい時間がかかりますか?
ほとんどのCoddyKitレッスンは約5~10分かかります。各レッスンはコンパクトでインタラクティブなので、着実に進歩し、ウェブとアプリ全体で正確に前回の場所から再開できます。
このZig Academyレッスンでコードを書いて実行できますか?
はい。すべてのZig Academyレッスンに組み込みコードエディタが含まれているため、ブラウザでリアルコードを書いて実行し、即座のAIフィードバックを取得できます。ローカル設定は不要です。