Форматирование текста с помощью std.fmt
Создавайте строки с помощью спецификаторов формата.
«Форматирование текста с помощью std.fmt» — бесплатный урок Zig Academy на CoddyKit. Это урок 4 из 4. Ты можешь прочитать весь урок бесплатно ниже — а потом практиковать его прямо в браузере с встроенным редактором кода и ИИ-репетитором 24/7. Это часть пути обучения Zig Academy, и твой прогресс синхронизируется между веб-версией и приложением CoddyKit. Курс Zig Academy содержит 4 уроков всего.
Части этого урока еще не переведены и отображаются на английском.
Why Formatting
Real programs stitch values into text: names, counts, prices. Zig handles this through std.fmt and its format-string mini-language.
Placeholders in Braces
A format string uses {} as a placeholder. Each pair of braces pulls the next argument from the tuple you pass alongside it.
std.debug.print("x = {}\n", .{42});Arguments Go in a Tuple
You supply arguments as an anonymous tuple, written .{ a, b }. Even a single argument lives inside that tuple wrapper.
std.debug.print("{} {}\n", .{1, 2});String Specifier
Print a []const u8 as text with {s}. A bare {} would try to format the slice as a struct of pointer and length instead.
std.debug.print("{s}\n", .{"hi"});Number Bases
Control an integer is base with specifiers like {x} for hex, {b} for binary, and {o} for octal. Great for low-level debugging.
std.debug.print("{x}\n", .{255}); // ffWidth and Padding
Pad a value to a fixed width using a colon, as in {d:5}. It lines numbers up neatly into clean, readable columns.
std.debug.print("{d:5}\n", .{7});Float Precision
Limit decimal places with a precision field like {d:.2}. This prints exactly two digits after the point for a tidy result.
std.debug.print("{d:.2}\n", .{3.14159});Escape a Brace
Need a literal curly brace in your output? Double it: {{ prints one { and }} prints one }. This avoids placeholder confusion.
std.debug.print("{{x}}\n", .{});Build a String
To format into memory instead of stdout, call std.fmt.allocPrint. It allocates and returns a fresh []u8 holding your text.
const s = try std.fmt.allocPrint(
alloc, "id={}", .{id});Free What You Allocate
Because allocPrint uses an allocator, you own the result and must free it. A defer right after the call keeps cleanup tidy.
defer alloc.free(s);Fixed Buffers with bufPrint
When you want no heap at all, write into your own array with std.fmt.bufPrint. It returns the filled-in slice it actually used.
var buf: [16]u8 = undefined;
const out = try std.fmt.bufPrint(&buf, "{}", .{9});Quick Check
You are printing a []const u8 value and want it shown as readable text.
Recap
You formatted text with std.fmt: {} and {s} placeholders, base, width, and precision, plus allocPrint and bufPrint for strings. 🎨
Часто задаваемые вопросы
Урок «Форматирование текста с помощью std.fmt» бесплатный?
Да — полный текст урока «Форматирование текста с помощью std.fmt» бесплатно доступен здесь в веб-версии. Чтобы практиковать его интерактивно (встроенный редактор кода и ИИ-репетитор 24/7) и разблокировать остальной курс Zig Academy, подпишись на CoddyKit PRO. Курс Zig Academy содержит 4 уроков всего.
Чему я научусь в уроке «Форматирование текста с помощью std.fmt»?
Создавайте строки с помощью спецификаторов формата. Ты практикуешь Zig Academy с помощью реального кода, который запускаешь прямо в браузере, и ИИ-репетитор 24/7 отвечает на твои вопросы во время урока.
Нужен ли мне опыт, чтобы начать Zig Academy?
Предыдущий опыт не требуется. Zig Academy на CoddyKit структурирован для всех уровней — от новичков до продвинутых, поэтому ты можешь начать отсюда или с самого начала и учиться в своем темпе. Это урок 4 из 4.
Сколько времени занимает урок «Форматирование текста с помощью std.fmt»?
Большинство уроков CoddyKit занимают около 5–10 минут. Каждый из них компактный и интерактивный, поэтому ты постоянно делаешь прогресс и продолжаешь с того же места в веб-версии и приложении.
Можно ли писать и запускать код в этом уроке Zig Academy?
Да. Каждый урок Zig Academy включает встроенный редактор кода, поэтому ты пишешь и запускаешь реальный код прямо в браузере и получаешь моментальную обратную связь от AI — локальная установка не требуется.
Все уроки этого курса
- Строки — это []const u8
- Строковые литералы и экранирование
- Сравнение и поиск байтов
- Форматирование текста с помощью std.fmt