Language
日本語
English

Caution

JavaScript is disabled in your browser.
This site uses JavaScript for features such as search.
For the best experience, please enable JavaScript before browsing this site.

  1. Home
  2. Zig Dictionary
  3. slice

slice

In Zig, slices let you reference a portion of an array or string. A slice is represented internally as a pointer and length pair, and provides a way to access a subset of data without copying it. This page covers the basic usage of slices and how they differ from arrays.

Syntax

// -----------------------------------------------
// Slice type declarations
// -----------------------------------------------

[]T          // Mutable slice (elements can be modified)
[]const T    // Constant slice (elements cannot be modified)
// T : element type (e.g., u8, i32, []const u8)

// -----------------------------------------------
// Creating a slice from an array (range syntax)
// -----------------------------------------------

const slice = array[start..end];
// start : starting index (inclusive)
// end   : ending index (exclusive)
// Example: array[1..4] references indices 1, 2, 3

const slice_to_end = array[start..];
// References all elements from start to the end of the array

const full_slice = array[0..];
// References the entire array as a slice

// -----------------------------------------------
// Slice length and element access
// -----------------------------------------------

slice.len          // Number of elements in the slice (type: usize)
slice[index]       // Index access (0-based)
slice[index] = v;  // Write to a mutable slice

Syntax Reference

Syntax / MethodDescription
[]TMutable slice type. Holds a reference to the original data and allows element modification.
[]const TConstant slice type. Elements referenced by the slice cannot be modified. String literals use the type []const u8.
array[start..end]Returns a slice covering indices from start (inclusive) to end (exclusive).
array[start..]Returns a slice from start to the end of the array.
array[0..]Returns a slice covering the entire array.
slice.lenReturns the number of elements referenced by the slice as type usize.
slice[i]Retrieves the element at index i. Out-of-bounds access causes a runtime error.
slice[i] = vWrites value v to index i of a mutable slice.
for (slice) |elem|Iterates over each element of the slice with a for loop.
for (slice, 0..) |elem, i|Iterates over each element of the slice with its index.

Sample Code

slice.zig
// slice.zig — demonstrates basic slice operations in Zig
// using Jujutsu Kaisen characters as sample data

const std = @import("std");

pub fn main() !void {
    const stdout = std.io.getStdOut().writer();

    // -----------------------------------------------
    // Define an array
    // [_] lets the compiler infer the element count automatically
    // -----------------------------------------------
    const sorcerers = [_][]const u8{
        "Gojo Satoru",    // index 0
        "Itadori Yuji",   // index 1
        "Fushiguro Megumi", // index 2
        "Kugisaki Nobara", // index 3
        "Nanami Kento",   // index 4
    };

    try stdout.print("=== Jujutsu Kaisen Sorcerers ===\n\n", .{});

    // -----------------------------------------------
    // Reference the entire array as a slice
    // [0..] means "from index 0 to the end"
    // -----------------------------------------------
    const all_sorcerers: []const []const u8 = sorcerers[0..];
    try stdout.print("All sorcerers ({d}):\n", .{all_sorcerers.len});
    for (all_sorcerers) |name| {
        try stdout.print("  - {s}\n", .{name});
    }

    try stdout.print("\n", .{});

    // -----------------------------------------------
    // Create a slice with a range
    // sorcerers[1..4] references indices 1, 2, 3
    // Index 4 is not included
    // -----------------------------------------------
    const students: []const []const u8 = sorcerers[1..4];
    try stdout.print("Tokyo Jujutsu High students ({d}):\n", .{students.len});
    for (students) |name| {
        try stdout.print("  - {s}\n", .{name});
    }

    try stdout.print("\n", .{});

    // -----------------------------------------------
    // Use the start.. syntax to slice to the end of the array
    // -----------------------------------------------
    const grade1_and_above: []const []const u8 = sorcerers[4..];
    try stdout.print("Grade 1 sorcerers and above ({d}):\n", .{grade1_and_above.len});
    for (grade1_and_above) |name| {
        try stdout.print("  - {s}\n", .{name});
    }

    try stdout.print("\n", .{});

    // -----------------------------------------------
    // Create a mutable slice from a mutable array and modify elements
    // Arrays declared with var can be changed
    // -----------------------------------------------
    var cursed_energy = [_]u32{ 100, 80, 75, 70, 90 };

    // Boost cursed energy (modifies the original array through the slice)
    const boost_targets: []u32 = cursed_energy[1..4];
    for (boost_targets) |*energy| {
        energy.* += 10; // Add value through a pointer
    }

    try stdout.print("After cursed energy boost (3 students +10):\n", .{});
    for (sorcerers, cursed_energy) |name, energy| {
        try stdout.print("  {s}: {d}\n", .{ name, energy });
    }

    try stdout.print("\n", .{});

    // -----------------------------------------------
    // Retrieve elements along with their indices
    // -----------------------------------------------
    const top3: []const []const u8 = sorcerers[0..3];
    try stdout.print("Top 3 (with index):\n", .{});
    for (top3, 0..) |name, i| {
        try stdout.print("  [{d}] {s}\n", .{ i, name });
    }
}
zig run slice.zig
=== Jujutsu Kaisen Sorcerers ===

All sorcerers (5):
  - Gojo Satoru
  - Itadori Yuji
  - Fushiguro Megumi
  - Kugisaki Nobara
  - Nanami Kento

Tokyo Jujutsu High students (3):
  - Itadori Yuji
  - Fushiguro Megumi
  - Kugisaki Nobara

Grade 1 sorcerers and above (1):
  - Nanami Kento

After cursed energy boost (3 students +10):
  Gojo Satoru: 100
  Itadori Yuji: 90
  Fushiguro Megumi: 85
  Kugisaki Nobara: 80
  Nanami Kento: 90

Top 3 (with index):
  [0] Gojo Satoru
  [1] Itadori Yuji
  [2] Fushiguro Megumi

Overview

A slice in Zig is a data type that references a portion of an array or another slice. Internally, it is represented as a "pointer + length (len)" pair. To create a slice from an array, use the range syntax array[start..end]. The end index itself is not included, so sorcerers[1..4] references three elements at indices 1, 2, and 3. To reference from a given index to the end, use array[start..]; to reference the entire array, use array[0..].

Slice types come in two forms: []T (mutable) and []const T (constant). When you write through a mutable slice using pointer syntax such as elem.*, the original array is also modified. This demonstrates that a slice is a reference, not a copy. The length of a slice is available via the .len field, and slices work naturally with for loops to process each element. For the basics of arrays themselves, see Arrays (Basics).

If you find any errors or copyright issues, please .