Slices in Zig
A slice is a pointer plus a length onto memory that already exists.
const std = @import("std");
pub fn main() void {
var week = [_]i32{ 61, 68, 74, 79, 72, 65, 58 };
// A slice is a pointer plus a length onto existing memory.
const midweek: []i32 = week[2..5];
std.debug.print("midweek: {any}\n", .{midweek});
std.debug.print("len {d}, first {d}\n", .{ midweek.len, midweek[0] });
// Writing through the slice writes the array underneath.
midweek[0] += 1;
std.debug.print("warmed wednesday: {d}\n", .{week[2]});
}
How it works
week[2..5]borrows three days of the array as[]i32..lentravels with the slice; indexing is bounds-checked in safe builds.- Writing
midweek[0]writes the array underneath — same bytes, two names.
Keywords and builtins used here
constfni32pubvarvoid
The run, in numbers
- Lines
- 14
- Characters to type
- 448
- Tokens
- 127
- Three-star pace
- 70 tpm
At the three-star pace of 70 tokens a minute, this run takes about 109 seconds.
Step 3 of 3 in Optionals & pointers, step 12 of 27 in Language basics.