0Pricing
Zig Academy · Урок

Функции, принимающие тип

Создавайте обобщённые функции с параметрами comptime T.

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

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

Generics, the Zig Way

Zig has no separate generics syntax. Instead, a function can accept a type as one of its parameters and use it like any other value. ✨

A Type Parameter Is comptime

Because a type must be known when the code is built, the type parameter is always marked comptime. The caller passes a real type.

fn first(comptime T: type, items: []const T) T {
    return items[0];
}

type Is a Real Type

In Zig the word type is itself a type, so a parameter can be declared as type to mean any type at all.

comptime T: type

Use T in the Signature

Once you name the type T, you can use it for later parameters and the return type, tying them all together.

fn max(comptime T: type, a: T, b: T) T {
    return if (a > b) a else b;
}

Calling a Generic Function

To call it, pass the concrete type first, then the regular arguments. Here we ask for the larger of two i32 values.

const m = max(i32, 3, 9);

One Function, Many Types

The same function works for any type that supports the operations you use. Swap i32 for f64 and the code still fits.

const f = max(f64, 1.5, 2.5);

Zig Specializes Each Call

For every distinct type you pass, Zig generates a dedicated copy of the function. This is monomorphization, done at compile time.

The Body Stays Generic

You write the type explicitly at the call, but the body stays generic. Zig checks that the operations you use are valid for whatever T arrives.

type Means No Hidden Boxing

Passing a real type is different from runtime polymorphism: there is no vtable and no boxing, just a concrete copy chosen at build time.

Errors Surface at Compile Time

If you call max with a type that has no greater-than operator, Zig reports the problem when it builds that specialization, not at run time.

Type Parameters Come First

By convention the comptime type parameter is listed before the value parameters, so the type is known before the data is described.

fn clone(comptime T: type, value: T) T {
    return value;
}

Quick Check

You want a function that works for many types in Zig. How do you declare its type parameter?

Recap

Pass a comptime T: type parameter to make a function generic. Zig builds a specialized version for every type you actually use. 🎯

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

Урок «Функции, принимающие тип» бесплатный?

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

Чему я научусь в уроке «Функции, принимающие тип»?

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

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

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

Сколько времени занимает урок «Функции, принимающие тип»?

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

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

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

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

  1. Функции, принимающие тип
  2. Обобщённые структуры данных
  3. @TypeOf и отражение типов
  4. Параметры anytype
← Назад к Zig Academy