0Pricing
Zig Academy · Урок

Создание типов с помощью @Type

Создавайте новые типы программно.

«Создание типов с помощью @Type» — бесплатный урок Zig Academy на CoddyKit. Это урок 2 из 4. Ты можешь прочитать весь урок бесплатно ниже — а потом практиковать его прямо в браузере с встроенным редактором кода и ИИ-репетитором 24/7. Это часть пути обучения Zig Academy, и твой прогресс синхронизируется между веб-версией и приложением CoddyKit. Курс Zig Academy содержит 4 уроков всего.

Части этого урока еще не переведены и отображаются на английском.

The Reverse of @typeInfo

If @typeInfo turns a type into data, @Type turns data back into a real type. Together they let you reshape types at compile time. 🛠️

Feed It a Type.Info Value

@Type takes a std.builtin.Type value and produces the concrete type it describes. You hand it a description, it gives you a type.

const T = @Type(.{ .Int = .{ .signedness = .unsigned, .bits = 8 } });

Build an Integer Type

The example above constructs u8 from scratch. Change bits to 16 and you get u16, all decided while the program compiles.

const U16 = @Type(.{ .Int = .{ .signedness = .unsigned, .bits = 16 } });

Round-Trip a Type

Passing a type through @typeInfo then @Type returns the very same type. This proves the two builtins are exact inverses.

const Same = @Type(@typeInfo(u32));

Describe a Struct as Data

To build a struct you fill in a StructField array. Each field needs a name, a type, alignment, and a default pointer.

const f = std.builtin.Type.StructField;

Assemble the Struct Payload

Wrap your fields in a .Struct payload with a layout and an is_tuple flag, then hand the whole thing to @Type.

const info = .{ .Struct = .{
    .layout = .auto,
    .fields = my_fields,
    .decls = &.{},
    .is_tuple = false,
} };

Generate a Fresh Struct Type

Call @Type on that payload and you get a brand-new struct type, built by your own logic rather than written by hand.

const Generated = @Type(info);

Defaults Need a Comptime Pointer

A field's default_value is an optional const pointer to the value, or null when there is no default. The pointer must be comptime-known.

const dv: ?*const anyopaque = &@as(u8, 0);

Build Enums and More

The same trick works beyond structs: the .Enum payload lets @Type synthesize enum types from a computed list of members.

Why Construct Types at All

Generated types power serializers and ORMs: derive a packed config or row type automatically instead of editing it by hand. ✨

Pair It with Reflection

The strongest pattern reads a type with @typeInfo, transforms the data, then rebuilds a new type with @Type, like adding a field.

Quick Check

You have a std.builtin.Type value describing a struct. What turns it into a usable type?

Recap

@Type builds real types from Type.Info data, the inverse of @typeInfo. Pair them to read, transform, and regenerate types. 🎯

Часто задаваемые вопросы

Урок «Создание типов с помощью @Type» бесплатный?

Да — полный текст урока «Создание типов с помощью @Type» бесплатно доступен здесь в веб-версии. Чтобы практиковать его интерактивно (встроенный редактор кода и ИИ-репетитор 24/7) и разблокировать остальной курс Zig Academy, подпишись на CoddyKit PRO. Курс Zig Academy содержит 4 уроков всего.

Чему я научусь в уроке «Создание типов с помощью @Type»?

Создавайте новые типы программно. Ты практикуешь Zig Academy с помощью реального кода, который запускаешь прямо в браузере, и ИИ-репетитор 24/7 отвечает на твои вопросы во время урока.

Нужен ли мне опыт, чтобы начать Zig Academy?

Предыдущий опыт не требуется. Zig Academy на CoddyKit структурирован для всех уровней — от новичков до продвинутых, поэтому ты можешь начать отсюда или с самого начала и учиться в своем темпе. Это урок 2 из 4.

Сколько времени занимает урок «Создание типов с помощью @Type»?

Большинство уроков CoddyKit занимают около 5–10 минут. Каждый из них компактный и интерактивный, поэтому ты постоянно делаешь прогресс и продолжаешь с того же места в веб-версии и приложении.

Можно ли писать и запускать код в этом уроке Zig Academy?

Да. Каждый урок Zig Academy включает встроенный редактор кода, поэтому ты пишешь и запускаешь реальный код прямо в браузере и получаешь моментальную обратную связь от AI — локальная установка не требуется.

Все уроки этого курса

  1. Рефлексия полей с помощью @typeInfo
  2. Создание типов с помощью @Type
  3. Проверка во время компиляции и @compileError
  4. Генерация кода с помощью comptime
← Назад к Zig Academy