0Pricing
Zig Academy · Урок

Строки — это []const u8

Почему строки Zig являются срезами байтов.

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

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

No String Type

Zig has no dedicated string type. A piece of text is simply a slice of bytes, so you reuse the same tools you already know for arrays. 📦

It Is Just Bytes

A Zig string is the type []const u8: a read-only window over a run of 8-bit bytes. Each byte holds one number from 0 to 255.

const greeting: []const u8 = "hello";

Why const

String literals live in read-only memory, so their type is []const u8. The const means you can read the bytes but never write through this slice.

u8 Is One Byte

The element type u8 is an unsigned 8-bit integer. Treating text as u8 makes Zig honest: a string is raw bytes, not magic characters.

A Slice Has a Length

A slice carries both a pointer and a length, so the string knows its own size. You never need a separate length variable or a terminator.

const name = "Zig";
// name.len == 3

UTF-8 by Convention

Zig source files are UTF-8, so literals store text as UTF-8 bytes. One emoji or accented letter may take several bytes, not one.

Length Counts Bytes

Because text is bytes, .len returns the byte count, not the character count. For plain ASCII the two numbers match exactly.

const s = "abc";
std.debug.print("{}", .{s.len}); // 3

Index Returns a Byte

Indexing a string gives you back a single u8 byte value, not a character object. For ASCII, that byte is the letter is code.

const s = "AB";
const first = s[0]; // 65, the A

No Null Terminator Needed

Unlike C, a Zig slice does not rely on a trailing zero byte to mark its end. The stored length already tells code where text stops.

Print a String

You print text with the {s} format specifier, which tells Zig to render the bytes as a string instead of as numbers.

std.debug.print("{s}\n", .{"hello"});

Mutable Bytes Need [] u8

Drop the const to get a writable []u8 slice. Then you can change bytes in place, as long as they live in memory you own.

Quick Check

Think about the real type behind a Zig string literal.

Recap

You learned that Zig text is just []const u8: read-only bytes with a length, UTF-8 by convention, indexed and measured in bytes. 🎯

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

Урок «Строки — это []const u8» бесплатный?

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

Чему я научусь в уроке «Строки — это []const u8»?

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

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

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

Сколько времени занимает урок «Строки — это []const u8»?

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

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

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

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

  1. Строки — это []const u8
  2. Строковые литералы и экранирование
  3. Сравнение и поиск байтов
  4. Форматирование текста с помощью std.fmt
← Назад к Zig Academy