Ваша первая функция main
Анатомия минимальной программы на Zig.
«Ваша первая функция main» — бесплатный урок Zig Academy на CoddyKit. Это урок 2 из 4. Ты можешь прочитать весь урок бесплатно ниже — а потом практиковать его прямо в браузере с встроенным редактором кода и ИИ-репетитором 24/7. Это часть пути обучения Zig Academy, и твой прогресс синхронизируется между веб-версией и приложением CoddyKit. Курс Zig Academy содержит 4 уроков всего.
Части этого урока еще не переведены и отображаются на английском.
Where Programs Begin
Every Zig executable starts at a function named main. The compiler looks for it and runs it first when your program launches. 🚀
Import the Standard Library
Most programs begin by pulling in tools. You bind the standard library to a name using @import, a built-in that loads a module.
const std = @import("std");Built-ins Start with @
Names beginning with @, like @import, are compiler built-ins. They are part of the language itself, not normal library functions.
Declaring main
You define main with the fn keyword. The simplest version takes no arguments and returns void, meaning it hands back no value.
pub fn main() void {
// your code runs here
}Why pub Matters
The pub keyword makes main visible outside its file so the runtime can call it. Without pub, the program cannot find an entry point.
void Means No Return
The void return type says main produces nothing. Many real programs instead return an error union so they can report failures.
The Function Body
Code inside the curly braces is the body. Statements there run top to bottom, exactly in the order you write them.
Add a First Statement
Inside main you can call functions. Here a single print statement greets the world from the standard library.
pub fn main() void {
std.debug.print("Hi from Zig!\n", .{});
}Statements End with Semicolons
Each statement finishes with a semicolon. Zig is precise about this, which keeps the boundaries between statements crystal clear.
Comments for Humans
Lines starting with two slashes are comments. Zig ignores them entirely, so use them to explain intent to future readers.
// This is a comment, ignored by the compiler
const answer = 42;The Whole First Program
Putting it together gives a complete, minimal Zig program: one import and one main function that prints a line.
const std = @import("std");
pub fn main() void {
std.debug.print("Hello!\n", .{});
}Quick Check
Look at a minimal Zig program. Which keyword exposes main so the program can actually start?
Recap
A Zig program starts at main: import std, declare pub fn main() void, and fill the body with statements that run in order. 🎯
Часто задаваемые вопросы
Урок «Ваша первая функция main» бесплатный?
Да — полный текст урока «Ваша первая функция main» бесплатно доступен здесь в веб-версии. Чтобы практиковать его интерактивно (встроенный редактор кода и ИИ-репетитор 24/7) и разблокировать остальной курс Zig Academy, подпишись на CoddyKit PRO. Курс Zig Academy содержит 4 уроков всего.
Чему я научусь в уроке «Ваша первая функция main»?
Анатомия минимальной программы на Zig. Ты практикуешь Zig Academy с помощью реального кода, который запускаешь прямо в браузере, и ИИ-репетитор 24/7 отвечает на твои вопросы во время урока.
Нужен ли мне опыт, чтобы начать Zig Academy?
Предыдущий опыт не требуется. Zig Academy на CoddyKit структурирован для всех уровней — от новичков до продвинутых, поэтому ты можешь начать отсюда или с самого начала и учиться в своем темпе. Это урок 2 из 4.
Сколько времени занимает урок «Ваша первая функция main»?
Большинство уроков CoddyKit занимают около 5–10 минут. Каждый из них компактный и интерактивный, поэтому ты постоянно делаешь прогресс и продолжаешь с того же места в веб-версии и приложении.
Можно ли писать и запускать код в этом уроке Zig Academy?
Да. Каждый урок Zig Academy включает встроенный редактор кода, поэтому ты пишешь и запускаешь реальный код прямо в браузере и получаешь моментальную обратную связь от AI — локальная установка не требуется.
Все уроки этого курса
- Установка Zig на любой платформе
- Ваша первая функция main
- Вывод с помощью std.debug.print
- Компиляция и запуск одним шагом