Skip to content
Language referenceZig 0.17.1Official documentation

A slice is a pointer and a length. The difference between an array and a slice is that the array's length is part of the type and known at compile-time, whereas the slice's length is known at runtime. Both can be accessed with the len field.

test_basic_slices.zig
const expectEqual = @import("std").testing.expectEqual;
const expectEqualSlices = @import("std").testing.expectEqualSlices;
test "basic slices" {
var array = [_]i32{ 1, 2, 3, 4 };
var known_at_runtime_zero: usize = 0;
_ = &known_at_runtime_zero;
const slice = array[known_at_runtime_zero..array.len];
// alternative initialization using result location
const alt_slice: []const i32 = &.{ 1, 2, 3, 4 };
try expectEqualSlices(i32, slice, alt_slice);
try expectEqual([]i32, @TypeOf(slice));
try expectEqual(&array[0], &slice[0]);
try expectEqual(array.len, slice.len);
// If you slice with comptime-known start and end positions, the result is
// a pointer to an array, rather than a slice.
const array_ptr = array[0..array.len];
try expectEqual(*[array.len]i32, @TypeOf(array_ptr));
// Using the address-of operator on a slice gives a single-item pointer.
try expectEqual(*i32, @TypeOf(&slice[0]));
// Using the `ptr` field gives a many-item pointer.
try expectEqual([*]i32, @TypeOf(slice.ptr));
try expectEqual(@intFromPtr(slice.ptr), @intFromPtr(&slice[0]));
// Slices have array bounds checking. If you try to access something out
// of bounds, you'll get a safety check failure:
slice[10] += 1;
// Note that `slice.ptr` does not invoke safety checking, while `&slice[0]`
// asserts that the slice has len > 0.
// Empty slices can be created like this:
const empty1 = &[0]u8{};
// If the type is known you can use this short hand:
const empty2: []u8 = &.{};
try expectEqual(0, empty1.len);
try expectEqual(0, empty2.len);
// A zero-length initialization can always be used to create an empty slice, even if the slice is mutable.
// This is because the pointed-to data is zero bits long, so its immutability is irrelevant.
}
Terminal
$ zig test test_basic_slices.zig
1/1 test_basic_slices.test.basic slices...thread 435663 panic: index out of bounds: index 10, len 4
/home/alexrp/Sources/ziglang/zig/doc/langref/test_basic_slices.zig:32:10: 0x1250a98 in test.basic slices (test_basic_slices.zig)
slice[10] += 1;
^
/home/alexrp/.cache/zig/p/N-V-__8AALBXTRYsilzupvrmv0afm7ohtj5Mj0paqVfKLmfP/lib/compiler/test_runner.zig:295:25: 0x1202c41 in mainTerminal (test_runner.zig)
if (test_fn.func()) |_| {
^
/home/alexrp/.cache/zig/p/N-V-__8AALBXTRYsilzupvrmv0afm7ohtj5Mj0paqVfKLmfP/lib/compiler/test_runner.zig:74:28: 0x1202422 in main (test_runner.zig)
return mainTerminal(init);
^
/home/alexrp/.cache/zig/p/N-V-__8AALBXTRYsilzupvrmv0afm7ohtj5Mj0paqVfKLmfP/lib/std/start.zig:789:88: 0x11febbf in callMain (std.zig)
if (fn_info.param_types[0].? == std.process.Init.Minimal) return wrapMain(root.main(.{
^
/home/alexrp/.cache/zig/p/N-V-__8AALBXTRYsilzupvrmv0afm7ohtj5Mj0paqVfKLmfP/lib/std/start.zig:248:5: 0x11fe5a1 in _start (std.zig)
asm volatile (switch (native_arch) {
^
error: the following test command terminated with signal ABRT:
/home/alexrp/Sources/ziglang/zig/.zig-cache/o/1f7a23f34f9e6bf89e5dd188e8421cb2/test --seed=0x752b51ec

This is one reason we prefer slices to pointers.

test_slices.zig
const std = @import("std");
const expectEqual = std.testing.expectEqual;
const expectEqualStrings = std.testing.expectEqualStrings;
const mem = std.mem;
test "using slices for strings" {
// Zig has no concept of strings. String literals are const pointers
// to null-terminated arrays of u8, and by convention parameters
// that are "strings" are expected to be UTF-8 encoded slices of u8.
// Here we coerce *const [5:0]u8 and *const [6:0]u8 to []const u8
const hello: []const u8 = "hello";
const world: []const u8 = "世界";
var all_together: [100]u8 = undefined;
// You can use slice syntax with at least one runtime-known index on an
// array to convert an array into a slice.
var start: usize = 0;
_ = &start;
const all_together_slice = all_together[start..];
// String concatenation example.
const hello_world = try mem.print(all_together_slice, "{s} {s}", .{ hello, world });
// Generally, you can use UTF-8 and not worry about whether something is a
// string. If you don't need to deal with individual characters, no need
// to decode.
try expectEqualStrings("hello 世界", hello_world);
}
test "slice pointer" {
var array: [10]u8 = undefined;
const ptr = &array;
try expectEqual(*[10]u8, @TypeOf(ptr));
// A pointer to an array can be sliced just like an array:
var start: usize = 0;
var end: usize = 5;
_ = .{ &start, &end };
const slice = ptr[start..end];
// The slice is mutable because we sliced a mutable pointer.
try expectEqual([]u8, @TypeOf(slice));
slice[2] = 3;
try expectEqual(3, array[2]);
// Again, slicing with comptime-known indexes will produce another pointer
// to an array:
const ptr2 = slice[2..3];
try expectEqual(1, ptr2.len);
try expectEqual(3, ptr2[0]);
try expectEqual(*[1]u8, @TypeOf(ptr2));
}
Terminal
$ zig test test_slices.zig
1/2 test_slices.test.using slices for strings...OK
2/2 test_slices.test.slice pointer...OK
All 2 tests passed.

See also:

Slicing by Length

Even though Zig only has syntax for slicing based on start and end indices, by slicing twice, one can express a slice by length operation.

The pattern [a .. a + b] is always better expressed [a..][0..b] because:

  • Slices are represented in memory as a pointer and length. Despite syntactically appearing as twice the work, it is actually one less subtraction in machine code.
  • If a is known at runtime and b is known at comptime, the former results in a slice but the latter results in a single-item pointer to an array, a generally more safe type because the length is compile-time known.
slicing_by_length.zig
const expectEqual = @import("std").testing.expectEqual;
test "example" {
var array = [_]i32{ 1, 2, 3, 4 };
var runtime_start: usize = 1;
_ = &runtime_start;
const length = 2;
const array_ptr_len = array[runtime_start..][0..length];
try expectEqual(*[length]i32, @TypeOf(array_ptr_len));
}
Terminal
$ zig test slicing_by_length.zig
1/1 slicing_by_length.test.example...OK
All 1 tests passed.

Sentinel-Terminated Slices

The syntax [:x]T is a slice which has a runtime-known length and also guarantees a sentinel value at the element indexed by the length. The type does not guarantee that there are no sentinel elements before that. Sentinel-terminated slices allow element access to the len index.

test_null_terminated_slice.zig
const std = @import("std");
const expectEqual = std.testing.expectEqual;
test "0-terminated slice" {
const slice: [:0]const u8 = "hello";
try expectEqual(5, slice.len);
try expectEqual(0, slice[5]);
}
Terminal
$ zig test test_null_terminated_slice.zig
1/1 test_null_terminated_slice.test.0-terminated slice...OK
All 1 tests passed.

Sentinel-terminated slices can also be created using a variation of the slice syntax data[start..end :x], where data is a many-item pointer, array or slice and x is the sentinel value.

test_null_terminated_slicing.zig
const std = @import("std");
const expectEqual = std.testing.expectEqual;
test "0-terminated slicing" {
var array = [_]u8{ 3, 2, 1, 0, 3, 2, 1, 0 };
var runtime_length: usize = 3;
_ = &runtime_length;
const slice = array[0..runtime_length :0];
try expectEqual([:0]u8, @TypeOf(slice));
try expectEqual(3, slice.len);
}
Terminal
$ zig test test_null_terminated_slicing.zig
1/1 test_null_terminated_slicing.test.0-terminated slicing...OK
All 1 tests passed.

Sentinel-terminated slicing asserts that the element in the sentinel position of the backing data is actually the sentinel value. If this is not the case, safety-checked Illegal Behavior results.

test_sentinel_mismatch.zig
const std = @import("std");
const expectEqual = std.testing.expectEqual;
test "sentinel mismatch" {
var array = [_]u8{ 3, 2, 1, 0 };
// Creating a sentinel-terminated slice from the array with a length of 2
// will result in the value `1` occupying the sentinel element position.
// This does not match the indicated sentinel value of `0` and will lead
// to a runtime panic.
var runtime_length: usize = 2;
_ = &runtime_length;
const slice = array[0..runtime_length :0];
_ = slice;
}
Terminal
$ zig test test_sentinel_mismatch.zig
1/1 test_sentinel_mismatch.test.sentinel mismatch...thread 433752 panic: sentinel mismatch: expected 0, found 1
/home/alexrp/Sources/ziglang/zig/doc/langref/test_sentinel_mismatch.zig:13:24: 0x124e9ff in test.sentinel mismatch (test_sentinel_mismatch.zig)
const slice = array[0..runtime_length :0];
^
/home/alexrp/.cache/zig/p/N-V-__8AALBXTRYsilzupvrmv0afm7ohtj5Mj0paqVfKLmfP/lib/compiler/test_runner.zig:295:25: 0x1202c41 in mainTerminal (test_runner.zig)
if (test_fn.func()) |_| {
^
/home/alexrp/.cache/zig/p/N-V-__8AALBXTRYsilzupvrmv0afm7ohtj5Mj0paqVfKLmfP/lib/compiler/test_runner.zig:74:28: 0x1202422 in main (test_runner.zig)
return mainTerminal(init);
^
/home/alexrp/.cache/zig/p/N-V-__8AALBXTRYsilzupvrmv0afm7ohtj5Mj0paqVfKLmfP/lib/std/start.zig:789:88: 0x11febbf in callMain (std.zig)
if (fn_info.param_types[0].? == std.process.Init.Minimal) return wrapMain(root.main(.{
^
/home/alexrp/.cache/zig/p/N-V-__8AALBXTRYsilzupvrmv0afm7ohtj5Mj0paqVfKLmfP/lib/std/start.zig:248:5: 0x11fe5a1 in _start (std.zig)
asm volatile (switch (native_arch) {
^
error: the following test command terminated with signal ABRT:
/home/alexrp/Sources/ziglang/zig/.zig-cache/o/49f7825c70f7fbc49187ff99c8a7f3ee/test --seed=0xd878a861

See also: