null и undefined
Два разных вида отсутствия.
«null и undefined» — бесплатный урок Zig Academy на CoddyKit. Это урок 4 из 4. Ты можешь прочитать весь урок бесплатно ниже — а потом практиковать его прямо в браузере с встроенным редактором кода и ИИ-репетитором 24/7. Это часть пути обучения Zig Academy, и твой прогресс синхронизируется между веб-версией и приложением CoddyKit. Курс Zig Academy содержит 4 уроков всего.
Части этого урока еще не переведены и отображаются на английском.
Two Words, Two Meanings
Zig has both null and undefined, and they are not the same. Mixing them up is a classic source of confusing bugs.
null Means No Value
null is a real, defined state: it says this optional intentionally holds nothing. It is a meaningful, checkable value.
const x: ?i32 = null;undefined Means Unspecified
undefined means the storage exists but its contents are garbage. You are promising to write a real value before you read it.
var buf: [4]u8 = undefined;Only Optionals Hold null
You can assign null only to optional types. A plain i32 will never accept it, because absence is not part of its type.
Any Type Can Be undefined
By contrast, almost any variable can start as undefined to reserve memory now and fill it in a moment later.
var total: i32 = undefined;Reading null Is Fine
Checking an optional against null is perfectly safe and expected; that is exactly how you detect an absent value.
Reading undefined Is a Bug
Reading a value that is still undefined is illegal behavior. Safe builds even fill it with 0xAA bytes to expose the mistake.
A Promise to Yourself
Think of undefined as a contract: you swear to assign before use. Break it and you read meaningless, unpredictable data.
Common Buffer Pattern
A frequent idiom is declaring a buffer as undefined, then immediately filling it from a read or a format call.
var line: [256]u8 = undefined;Pick the Right Tool
Use null to model genuine optionality. Use undefined only to skip a redundant initialization you will overwrite right away.
Different Questions Entirely
null answers is there a value, while undefined answers has the memory been written yet. Keeping them separate keeps you safe.
Quick Check
You declare var buf: [8]u8 = undefined; and read buf[0] before writing it. What is that?
Recap
You separated null (a real absent value for optionals) from undefined (uninitialized memory you must write first). Two ideas, never confused. 🧠
Часто задаваемые вопросы
Урок «null и undefined» бесплатный?
Да — полный текст урока «null и undefined» бесплатно доступен здесь в веб-версии. Чтобы практиковать его интерактивно (встроенный редактор кода и ИИ-репетитор 24/7) и разблокировать остальной курс Zig Academy, подпишись на CoddyKit PRO. Курс Zig Academy содержит 4 уроков всего.
Чему я научусь в уроке «null и undefined»?
Два разных вида отсутствия. Ты практикуешь Zig Academy с помощью реального кода, который запускаешь прямо в браузере, и ИИ-репетитор 24/7 отвечает на твои вопросы во время урока.
Нужен ли мне опыт, чтобы начать Zig Academy?
Предыдущий опыт не требуется. Zig Academy на CoddyKit структурирован для всех уровней — от новичков до продвинутых, поэтому ты можешь начать отсюда или с самого начала и учиться в своем темпе. Это урок 4 из 4.
Сколько времени занимает урок «null и undefined»?
Большинство уроков CoddyKit занимают около 5–10 минут. Каждый из них компактный и интерактивный, поэтому ты постоянно делаешь прогресс и продолжаешь с того же места в веб-версии и приложении.
Можно ли писать и запускать код в этом уроке Zig Academy?
Да. Каждый урок Zig Academy включает встроенный редактор кода, поэтому ты пишешь и запускаешь реальный код прямо в браузере и получаешь моментальную обратную связь от AI — локальная установка не требуется.
Все уроки этого курса
- Объявление необязательных типов
- Безопасная распаковка с помощью if и orelse
- Необязательные указатели и ?*T
- null и undefined