TExcelTAD
Home › Zig › Zig Slices

Zig Slices

A slice is a view into a run of elements that lives somewhere else — inside an array, inside heap memory, or inside another slice. Under the hood it is just two things: a pointer to the first element and a length. Slices are how Zig functions accept "some number of items" without caring where they are stored.

Type Meaning
[]T slice of T whose elements may be changed
[]const T read-only slice of T

Slicing an array

The syntax array[start..end] creates a slice from index start up to, but not including, end. Leave out end to go to the last element.

zig · try it yourself
const std = @import("std");

pub fn main() void {
    const temps = [_]i32{ 18, 21, 25, 23, 19, 16 };

    const week_start = temps[0..3];
    const rest = temps[3..];
    const all = temps[0..];

    std.debug.print("start: {any} (len {d})\n", .{ week_start, week_start.len });
    std.debug.print("rest:  {any}\n", .{rest});
    std.debug.print("all has {d} items\n", .{all.len});
}
start: { 18, 21, 25 } (len 3)
rest:  { 23, 19, 16 }
all has 6 items

Note: When both bounds are compile-time constants, the result is actually a pointer to an array (like *const [3]i32), which converts to a slice automatically. You rarely need to care about the difference.

Functions take slices

This is where slices shine. One function can process arrays of any length:

zig · try it yourself
const std = @import("std");

fn sum(values: []const i32) i32 {
    var total: i32 = 0;
    for (values) |v| total += v;
    return total;
}

pub fn main() void {
    const small = [_]i32{ 1, 2, 3 };
    const big = [_]i32{ 10, 20, 30, 40, 50 };

    std.debug.print("{d}\n", .{sum(&small)}); // &array -> slice
    std.debug.print("{d}\n", .{sum(&big)});
    std.debug.print("{d}\n", .{sum(big[1..4])});
    std.debug.print("{d}\n", .{sum(&.{})}); // empty
}
6
150
90
0

Passing &small gives a pointer to the array, which Zig coerces to a slice. Using []const i32 instead of []i32 makes it clear the function only reads.

Modifying through a slice

A slice does not copy anything. Writing through a mutable slice changes the underlying array:

zig · try it yourself
const std = @import("std");

fn fillWith(dest: []u8, value: u8) void {
    for (dest) |*d| d.* = value;
}

pub fn main() void {
    var buffer = [_]u8{ 0, 0, 0, 0, 0, 0 };
    fillWith(buffer[1..4], 7);
    std.debug.print("{any}\n", .{buffer});

    const view = buffer[2..];
    view[0] = 42; // changes buffer[2]
    std.debug.print("{any}\n", .{buffer});
}
{ 0, 7, 7, 7, 0, 0 }
{ 0, 7, 42, 7, 0, 0 }

Bounds are checked

A slice knows its length, so indexing past it is caught in safe build modes (index out of bounds), and so is creating a slice whose end is beyond the array (slice end out of bounds). A start larger than the end is also rejected.

Useful std.mem functions

The std.mem namespace contains generic helpers that all work on slices:

Function What it does
std.mem.eql(T, a, b) are two slices equal?
std.mem.indexOfScalar(T, s, x) first index of x, or null
std.mem.max(T, s) / min largest / smallest element
std.mem.reverse(T, s) reverse in place
std.mem.sort(T, s, {}, std.sort.asc(T)) sort in place
@memcpy(dest, src) copy elements (same length)
@memset(dest, x) set every element to x
zig · try it yourself
const std = @import("std");

pub fn main() void {
    var data = [_]i32{ 42, 7, 19, 3, 25 };

    std.debug.print("max={d} min={d}\n", .{ std.mem.max(i32, &data), std.mem.min(i32, &data) });
    std.debug.print("index of 19: {?d}\n", .{std.mem.indexOfScalar(i32, &data, 19)});
    std.debug.print("index of 8: {?d}\n", .{std.mem.indexOfScalar(i32, &data, 8)});

    std.mem.sort(i32, &data, {}, std.sort.asc(i32));
    std.debug.print("sorted: {any}\n", .{data});
    std.mem.reverse(i32, &data);
    std.debug.print("reversed: {any}\n", .{data});
}
max=42 min=3
index of 19: 2
index of 8: null
sorted: { 3, 7, 19, 25, 42 }
reversed: { 42, 25, 19, 7, 3 }

Arrays vs slices

Array [N]T Slice []T
Length known at compile time at runtime
Owns its data yes no, it is a view
Assignment copies all elements copies only pointer + length
Typical use fixed-size buffers, tables function parameters, dynamic data

Test yourself

Which elements does arr[1..3] contain?

  1. arr[1], arr[2], arr[3]
  2. arr[1], arr[2]
  3. arr[0] to arr[3]
  4. arr[2], arr[3]

What does a slice consist of?

  1. A copy of the elements
  2. A pointer and a length
  3. Only a pointer
  4. A pointer, length and capacity

Why prefer []const u8 over []u8 for a parameter that is only read?

  1. It is faster
  2. It documents read-only intent and also accepts constant data
  3. It copies the data
  4. It is required by Zig