Zig Slices
If there’s one type you’ll see everywhere in Zig, it’s the slice. A slice is a view of some items in a row: all of an array, part of it, or memory you got from an allocator. Strings are slices, function parameters for lists are slices, and most of the standard library takes and returns slices. The good news: after arrays and pointers, there’s only one new idea here, and it’s a simple one.
What a slice is
Section titled “What a slice is”A slice is a pointer plus a length. It doesn’t hold the items itself; it points at items that live somewhere else (often in an array) and remembers how many there are. Its type is written []T, with nothing between the brackets:
const std = @import("std");
pub fn main() void { var temps = [_]i32{ 12, 15, 9, 20, 18, 11 };
const middle = temps[1..4]; const from_three = temps[3..]; const everything = temps[0..]; const nothing = temps[2..2];
std.debug.print("middle: {any}\n", .{middle}); std.debug.print("from_three: {any}\n", .{from_three}); std.debug.print("everything has {d} items\n", .{everything.len}); std.debug.print("nothing has {d} items\n", .{nothing.len});}Output:
middle: { 15, 9, 20 }from_three: { 20, 18, 11 }everything has 6 itemsnothing has 0 itemsThe slicing syntax is array[start..end]:
startis included,endisn’t.temps[1..4]is items 1, 2 and 3. The length is alwaysend - start.- Leave out the end to go to the last item:
temps[3..]. temps[0..]is the whole array, andtemps[2..2]is an empty slice. Empty slices are fine and common.
If you know Python’s list[1:4] or JavaScript’s arr.slice(1, 4), it’s the same idea, with .. instead of : and no negative indexes.
Slices are views, not copies
Section titled “Slices are views, not copies”Slicing never copies anything. A slice points at the original items, so a change through the slice is a change to the array:
const std = @import("std");
pub fn main() void { var temps = [_]i32{ 12, 15, 9, 20, 18, 11 }; const week_start = temps[0..3]; week_start[0] = 100; std.debug.print("{any}\n", .{temps});}Output:
{ 100, 15, 9, 20, 18, 11 }That’s what makes slices cheap: a slice is two numbers, an address and a length, however many items it covers. On our 64-bit Linux machine, @sizeOf([]i32) is 16 bytes, 8 for each. It also means a slice is only valid as long as the items it points at are alive, the same rule you learned about pointers in Zig Pointers.
A small detail: sometimes you get an array pointer
Section titled “A small detail: sometimes you get an array pointer”If you check the types, you’ll notice something:
const std = @import("std");
pub fn main() void { var temps = [_]i32{ 12, 15, 9, 20, 18, 11 }; var start: usize = 1; start += 0; const runtime = temps[start..4]; const fixed = temps[1..4]; std.debug.print("{}\n{}\n", .{ @TypeOf(runtime), @TypeOf(fixed) });}Output:
[]i32*[3]i32When start is only known while running, you get a real slice, []i32. When both ends are known while compiling, Zig knows the length is exactly 3, so it gives you a pointer to an array of 3, *[3]i32, which carries even more information. (start += 0 is just a trick to make start a run-time value for this example.)
You don’t need to worry about the difference: a *[3]i32 turns into a []i32 automatically wherever a slice is expected. Just don’t be surprised when an error message or @TypeOf shows the array-pointer type.
[]const T: a read-only slice
Section titled “[]const T: a read-only slice”Like pointers, slices come in two flavours. []T lets you change the items; []const T only lets you read them:
pub fn main() void { var temps = [_]i32{ 12, 15, 9 }; const ro: []const i32 = &temps; ro[0] = 1;}main.zig:4:7: error: cannot assign to constant ro[0] = 1; ~~^~~A slice of a const array is always []const. And []T turns into []const T automatically, so a function that takes []const T accepts both. The text type you’ve been using, []const u8, is exactly this: a read-only slice of bytes.
Slices in functions
Section titled “Slices in functions”This is where slices really earn their place. A function that takes a slice works for any length, and for any part of an array:
const std = @import("std");
fn largest(values: []const i32) i32 { var best = values[0]; for (values[1..]) |v| { if (v > best) best = v; } return best;}
pub fn main() void { const nums = [_]i32{ 4, -2, 17, 8 }; std.debug.print("{d}\n", .{largest(&nums)}); std.debug.print("{d}\n", .{largest(nums[0..2])});}Output:
174&nums gives a pointer to the whole array, which becomes a slice. nums[0..2] passes only the first two items. Inside, values[1..] is a slice of a slice: everything but the first item. Slicing a slice works exactly like slicing an array.
Forget the &, and Zig reminds you:
const std = @import("std");
fn total(values: []const i32) i32 { var sum: i32 = 0; for (values) |v| sum += v; return sum;}
pub fn main() void { const week = [_]i32{ 12, 15, 9 }; std.debug.print("{d}\n", .{total(week)});}main.zig:11:38: error: array literal requires address-of operator (&) to coerce to slice type '[]const i32' std.debug.print("{d}\n", .{total(week)}); ^~~~The array is a value; the slice needs to know where it is. &week gives it the address.
Bounds are always checked
Section titled “Bounds are always checked”If the compiler can see a slice goes past the end, the build fails:
pub fn main() void { var temps = [_]i32{ 12, 15, 9 }; temps[0] = 1; const x = temps[1..5]; _ = x;}main.zig:4:24: error: end index 5 out of bounds for array of length 3 const x = temps[1..5]; ^When the numbers are only known at run time, the check happens when the line runs:
const std = @import("std");
fn firstN(items: []const u8, n: usize) []const u8 { return items[0..n];}
pub fn main() void { const word = "zig"; std.debug.print("{s}\n", .{firstN(word, 2)}); std.debug.print("{s}\n", .{firstN(word, 5)});}You’ll see something like:
zithread 23843 panic: index out of bounds: index 5, len 3main.zig:4:17: 0x11e510e in firstN (main.zig) return items[0..n]; ^A start bigger than the end, like items[3..2], panics too, with start index 3 is larger than end index 2. Like array indexes, these checks are on in debug and safe builds. The reference on slices shows them in action.
Copying and filling
Section titled “Copying and filling”Since slices are views, var b = slice; only copies the pointer and the length, not the items. To copy the items themselves, use @memcpy(destination, source). To fill a slice with one value, use @memset:
const std = @import("std");
pub fn main() void { const source = [_]u8{ 1, 2, 3, 4, 5 }; var dest: [3]u8 = undefined; @memcpy(&dest, source[0..3]); std.debug.print("{any}\n", .{dest});
var buf: [8]u8 = @splat(0); @memcpy(buf[2..5], &dest); @memset(buf[0..2], 9); std.debug.print("{any}\n", .{buf});
std.mem.reverse(u8, buf[0..5]); std.debug.print("{any}\n", .{buf});}Output:
{ 1, 2, 3 }{ 9, 9, 1, 2, 3, 0, 0, 0 }{ 3, 2, 1, 9, 9, 0, 0, 0 }@memcpyneeds both sides to have the same length. If they don’t, it fails at compile time when it can tell, or panics withsource and destination arguments have non-equal lengths.buf[2..5]as a destination writes into the middle ofbuf. Slicing is how you aim at part of an array.std.mem.reversereverses the items in place. Thestd.memnamespace has many more helpers like this, which you’ll meet in Zig Strings in Depth.
Practice
Section titled “Practice”1. Sum of the middle
Section titled “1. Sum of the middle”Write sum(values: []const i32) i32 and use it to add up only the middle three items of { 1, 10, 20, 30, 2 }.
Hint: the middle three are nums[1..4].
Show solution
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 nums = [_]i32{ 1, 10, 20, 30, 2 }; std.debug.print("middle sum: {d}\n", .{sum(nums[1..4])}); std.debug.print("full sum: {d}\n", .{sum(&nums)});}Output:
middle sum: 60full sum: 63The same function handles part of the array or all of it, because it only sees a slice.
2. Two halves
Section titled “2. Two halves”Split { 1, 2, 3, 4, 5, 6, 7 } into a front half and a back half using slices, and print both. With an odd length, the extra item goes in the back.
Hint: compute const mid = nums.len / 2;, then nums[0..mid] and nums[mid..].
Show solution
const std = @import("std");
pub fn main() void { const nums = [_]i32{ 1, 2, 3, 4, 5, 6, 7 }; const mid = nums.len / 2; const front = nums[0..mid]; const back = nums[mid..]; std.debug.print("front: {any}\nback: {any}\n", .{ front, back });}Output:
front: { 1, 2, 3 }back: { 4, 5, 6, 7 }7 / 2 is 3 with whole-number division, so the front gets 3 items and the back gets the other 4. No item is copied.
3. Reverse in place
Section titled “3. Reverse in place”Write reverse(items: []u8) void yourself (without std.mem.reverse) and use it to turn "stressed" into "desserts".
Hint: swap items[i] and items[items.len - 1 - i] for i from 0 up to half the length. Copy the text into a var array first with var word = "stressed".*;, since string literals can’t be changed.
Show solution
const std = @import("std");
fn reverse(items: []u8) void { var i: usize = 0; while (i < items.len / 2) : (i += 1) { const j = items.len - 1 - i; const tmp = items[i]; items[i] = items[j]; items[j] = tmp; }}
pub fn main() void { var word = "stressed".*; reverse(&word); std.debug.print("{s}\n", .{word});}Output:
desserts"stressed".* copies the literal’s bytes into a [8]u8 array you own. &word then gives reverse a changeable slice of it.
- A slice
[]Tis a pointer plus a length: a view of items that live somewhere else. a[start..end]includesstartand excludesend;a[start..]goes to the end. Slices of slices work the same way.- Slicing never copies. Changing items through a
[]Tchanges the original. []const Tis read-only, and[]Tturns into it automatically. Text is[]const u8.- Take slices as parameters, and pass arrays with
&arrayor a part witharray[1..3]. - Bounds are checked: at compile time when possible, otherwise with a panic in safe builds.
- Copy items with
@memcpy(same lengths), fill with@memset.
Next up: Zig Sentinel-Terminated Types, arrays, slices and pointers that end with a special value, like C strings.
Quick check
Section titled “Quick check”Quick check
Read more
Section titled “Read more”- Zig language reference: Slices: slices, bounds checking, and slicing with known and unknown lengths.
- Zig language reference: Type Coercion of slices, arrays and pointers: when
*[N]Tturns into[]Tand other automatic conversions. - Zig language reference: @memcpy: the rules for copying between slices.
- Zig language reference: @memset: filling a slice with one value.