0Pricing
Zig Academy · Урок

Функции pub и видимость

Открывайте функции для использования в других файлах.

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

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

Files Are Modules

In Zig every source file is its own module. What it shares with other files is controlled by visibility rules. 📦

Private by Default

A plain function is private to its file. Other files cannot call it, which keeps internal helpers safely hidden.

fn helper() void {
    // only this file can call me
}

pub Makes It Public

Add the pub keyword to expose a function so other files can import and call it across your project.

pub fn greet() void {
    std.debug.print("Hi!\n", .{});
}

Import Brings It In

Another file uses @import to load your module, then reaches public names through the returned value.

const utils = @import("utils.zig");
utils.greet();

Only pub Names Are Reachable

Through that import you can call only the public names. Private functions stay invisible, so they cannot be misused.

Why main Needs pub

This is why main is written pub: the runtime lives outside your file and must be able to reach the entry point.

pub Works on More Than fn

The pub keyword also exposes constants, types, and variables, letting you publish a clean public surface for a module.

pub const version = "1.0.0";

Design a Small API

Mark only what callers truly need as public. Keeping helpers private gives you a small, stable interface to maintain.

Encapsulation Reduces Bugs

Hiding internals is encapsulation. With fewer exposed parts, you can change implementation details without breaking other files.

No Headers Needed

Unlike C, Zig needs no header files. Importing a file gives you its public declarations directly, with no duplication.

Visibility Is Compile-Time

Zig enforces visibility at compile time. Calling a private function from outside its file simply fails to compile.

Quick Check

You wrote a function in math.zig and another file cannot call it. What is most likely missing?

Recap

Functions are private to their file until you add pub. Expose only what callers need, import with @import, and skip headers entirely. 🎯

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

Урок «Функции pub и видимость» бесплатный?

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

Чему я научусь в уроке «Функции pub и видимость»?

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

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

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

Сколько времени занимает урок «Функции pub и видимость»?

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

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

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

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

  1. Синтаксис функций и возвращаемые типы
  2. Передача значений и ссылок
  3. Функции pub и видимость
  4. Рекурсия и несколько возвращаемых значений
← Назад к Zig Academy