0Pricing
Zig Academy · Урок

Создание срезов с помощью array[start..end]

Создавайте представления подмассивов без копирования.

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

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

Carving Out a View

Sometimes you want only part of an array. Slicing lets you grab a sub-range as a new slice without copying any elements. ✂️

The Range Syntax

Write the start and end inside brackets joined by two dots: array[start..end]. This produces a slice over those positions.

const part = data[1..3];

End Is Exclusive

The end index is exclusive, so array[1..3] includes positions 1 and 2 but stops before 3. The result has a length of 2.

Slice to the End

Leave the end off to run all the way to the last element. data[2..] means everything from index 2 onward.

const tail = data[2..];

Slice the Whole Thing

Using [0..] turns an entire array into a slice. It is the common way to hand a full array to slice-taking code.

const all = data[0..];

No Copy Happens

Slicing only computes a new pointer and length. The elements stay shared with the original array, so it is fast and allocation-free.

Slicing a Slice

You can slice a slice just like an array. The new range is relative to the slice's own start, narrowing the view further.

const inner = part[0..1];

Out-of-Range Is Caught

If start or end falls outside the data, safe builds panic at runtime. This stops you from reading memory you never owned.

Compile-Time Slices

When the bounds are known at compile time, the result can be a pointer to an array with a fixed length baked into its type.

Sentinel-Terminated Slices

Add a terminator with [start..end :0] to guarantee a trailing zero. This is handy when passing strings to C code.

const cstr = buf[0..n :0];

Length from the Range

A slice's length is simply end minus start. So data[2..5] always yields a slice whose len is exactly 3.

const three = data[2..5]; // len == 3

Quick Check

You have const data = [_]i32{ 0, 1, 2, 3, 4 }. What is the length of data[1..4]?

Recap

The array[start..end] syntax carves a sub-view: end is exclusive, omit it for the tail, nothing is copied, and bounds stay checked. 🎯

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

Урок «Создание срезов с помощью array[start..end]» бесплатный?

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

Чему я научусь в уроке «Создание срезов с помощью array[start..end]»?

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

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

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

Сколько времени занимает урок «Создание срезов с помощью array[start..end]»?

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

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

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

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

  1. Массивы фиксированного размера
  2. Срезы: указатель плюс длина
  3. Создание срезов с помощью array[start..end]
  4. Перебор и изменение срезов
← Назад к Zig Academy