Рефлексия полей с помощью @typeInfo
Исследуйте структуру типа во время компиляции.
«Рефлексия полей с помощью @typeInfo» — бесплатный урок Zig Academy на CoddyKit. Это урок 1 из 4. Ты можешь прочитать весь урок бесплатно ниже — а потом практиковать его прямо в браузере с встроенным редактором кода и ИИ-репетитором 24/7. Это часть пути обучения Zig Academy, и твой прогресс синхронизируется между веб-версией и приложением CoddyKit. Курс Zig Academy содержит 4 уроков всего.
Части этого урока еще не переведены и отображаются на английском.
Look Inside Any Type
Zig lets your code examine its own types while it compiles. The built-in @typeInfo hands you the full structure of a type as data. 🔎
It Returns a Type.Info Value
@typeInfo takes a type and returns a std.builtin.Type value. That value is a tagged union describing exactly what kind of type you passed.
const info = @typeInfo(u32);The Tag Says What Kind It Is
The union tag tells you the category: a struct, an int, a pointer, and so on. You switch on it to react to each kind of type.
switch (@typeInfo(T)) {
.Struct => {},
else => {},
}Reach the Struct Payload
When the type is a struct, the .Struct variant carries a payload describing its fields, declarations, and layout.
const s = @typeInfo(Point).Struct;Fields Live in an Array
The struct payload has a fields array. Each entry is a StructField holding one field's name, type, and other details.
const fields = @typeInfo(Point).Struct.fields;Read a Field's Name and Type
Each StructField exposes a name string and a type. Both are compile-time values you can print or branch on.
const f = @typeInfo(Point).Struct.fields[0];
const n = f.name;Walk Fields with inline for
Because the field list is comptime, you iterate it with inline for. The loop unrolls, giving each field its own concrete code.
inline for (@typeInfo(T).Struct.fields) |field| {
_ = field.name;
}Inspect Integer Types Too
For an int, the .Int variant reveals its signedness and bit width, so you can adapt logic to the exact number type.
const i = @typeInfo(i16).Int;
const bits = i.bits;Enums Expose Their Members
The .Enum variant lists every enum field with its name and integer value, letting you generate code per option.
const e = @typeInfo(Color).Enum;
const fields = e.fields;Pointers Reveal Their Target
For pointers the .Pointer variant tells you the child type, size kind, and whether it is const, so you can unwrap layers.
const p = @typeInfo(*u8).Pointer;
const child = p.child;This Powers Real Libraries
Reflection drives Zig's own JSON and formatting code: they read fields with @typeInfo and handle any struct you give them. ✨
Quick Check
You want the list of a struct's fields at compile time. Which expression gives it to you?
Recap
@typeInfo turns a type into data: switch on its tag, then read fields, bits, or members and loop them with inline for. 🎯
Часто задаваемые вопросы
Урок «Рефлексия полей с помощью @typeInfo» бесплатный?
Да — полный текст урока «Рефлексия полей с помощью @typeInfo» бесплатно доступен здесь в веб-версии. Чтобы практиковать его интерактивно (встроенный редактор кода и ИИ-репетитор 24/7) и разблокировать остальной курс Zig Academy, подпишись на CoddyKit PRO. Курс Zig Academy содержит 4 уроков всего.
Чему я научусь в уроке «Рефлексия полей с помощью @typeInfo»?
Исследуйте структуру типа во время компиляции. Ты практикуешь Zig Academy с помощью реального кода, который запускаешь прямо в браузере, и ИИ-репетитор 24/7 отвечает на твои вопросы во время урока.
Нужен ли мне опыт, чтобы начать Zig Academy?
Предыдущий опыт не требуется. Zig Academy на CoddyKit структурирован для всех уровней — от новичков до продвинутых, поэтому ты можешь начать отсюда или с самого начала и учиться в своем темпе. Это урок 1 из 4.
Сколько времени занимает урок «Рефлексия полей с помощью @typeInfo»?
Большинство уроков CoddyKit занимают около 5–10 минут. Каждый из них компактный и интерактивный, поэтому ты постоянно делаешь прогресс и продолжаешь с того же места в веб-версии и приложении.
Можно ли писать и запускать код в этом уроке Zig Academy?
Да. Каждый урок Zig Academy включает встроенный редактор кода, поэтому ты пишешь и запускаешь реальный код прямо в браузере и получаешь моментальную обратную связь от AI — локальная установка не требуется.
Все уроки этого курса
- Рефлексия полей с помощью @typeInfo
- Создание типов с помощью @Type
- Проверка во время компиляции и @compileError
- Генерация кода с помощью comptime