🎓 A1Learner
🔍
0 of 55 lessons completed

Zig Slices

A slice is a view into part of an existing array. It remembers where the view starts and how many values it covers.

A slice covers the first two values

The slice starts at index 0 and ends before index 2. The printout shows the covered values and their count.

const std = @import("std");

pub fn main() !void {
    const out = std.io.getStdOut().writer();
    const nums = [_]i32{ 3, 1, 4, 1, 5 };
    const part = nums[0..2];
    try out.print("{any}\n", .{part});
    try out.print("{d}\n", .{part.len});
}

The slice shows the new array value

The slice is taken first, and the array changes after that. The slice prints the new value, because it is a view and not a copy.

const std = @import("std");

pub fn main() !void {
    const out = std.io.getStdOut().writer();
    var nums = [_]i32{ 3, 1, 4, 1, 5 };
    const part = nums[1..3];
    nums[1] = 9;
    try out.print("{any}\n", .{part});
}

A function sums any slice

The sum function accepts a slice, so the caller chooses which part to add. The slice from index 2 to the end adds to 10.

const std = @import("std");

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

pub fn main() !void {
    const out = std.io.getStdOut().writer();
    const nums = [_]i32{ 3, 1, 4, 1, 5 };
    try out.print("{d}\n", .{sum(nums[2..5])});
}

Example

const std = @import("std");

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

pub fn main() !void {
    const out = std.io.getStdOut().writer();
    const readings = [_]i32{ 8, 12, 15, 11, 9 };
    const first = readings[0..2];
    try out.print("{any}\n", .{first});
    try out.print("{d}\n", .{first.len});
    try out.print("{d}\n", .{sum(first)});
    try out.print("{d}\n", .{sum(readings[2..5])});
}

Key points

  • Slice syntax: nums[0..2] takes a slice that starts at index 0 and ends before index 2.
  • End index: the end index is left out, so nums[0..2] covers two values.
  • Length: a slice has a .len that counts the values inside the view.
  • View: a slice does not copy the values it covers.
  • Live view: changing the array changes what an existing slice shows.
  • Slice parameter: a function can accept a slice and work with a view of any length.

In this example, first is a slice covering the first two readings. Its length is 2 and the sum function adds it to 20. A second slice covers the last three readings and adds to 35.

Note

a slice carries a pointer and a length inside, in plain words an address plus a count.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

How many values does nums[1..4] cover?