Arrays and Slices

9.1 Arrays (Fixed Length, Value Type)

Out-of-bounds indexing is a compile error (comptime index) or a runtime panic (safe modes).

const a = [5]i32{ 1, 2, 3, 4, 5 };
const b = [_]u8{ 'h', 'i' };                // _ infers length
var zeros = [_]u32{0} ** 10;                // repetition: 10 zeros
const c = a ++ [_]i32{ 6, 7 };              // concatenation (comptime-known)
var grid: [3][3]u8 = undefined;             // multidimensional
var filled: [100]u8 = @splat(0);            // fill with a value (0.14+)
std.debug.print("{d} {d}\n", .{ a.len, a[0] });
zeros[2] = 7;
const copy = a;                             // arrays are values: this copies

9.2 Slices (Pointer + Length)

[]T = mutable slice. []const T = read-only slice. Prefer []const T for parameters.

Slicing with comptime-known bounds gives an array pointer *[N]T.

var arr = [_]i32{ 10, 20, 30, 40, 50 };
const s: []i32 = arr[1..4];          // {20, 30, 40}; a slice is a fat pointer {ptr, len}
const tail = arr[2..];               // to the end
const all: []const i32 = &arr;       // array pointer coerces to a slice
s[0] = 99;                           // modifies arr (slices are views)
std.debug.print("{d} {any}\n", .{ s.len, s });

9.3 Sentinel-Terminated Arrays and Slices

const str: [:0]const u8 = "hello";        // length 5, plus a guaranteed 0 at str[5]
const arr: [3:0]u8 = .{ 1, 2, 3 };
const cstr: [*:0]const u8 = str.ptr;      // many-item pointer terminated by 0 (C strings)
const len = std.mem.len(cstr);            // compute the length by scanning for the sentinel
const back: [:0]const u8 = std.mem.span(cstr);

9.4 Common std.mem Operations

const mem = std.mem;
_ = mem.eql(u8, "abc", "abc");                       // equality (never use == on slices)
_ = mem.indexOf(u8, "hello", "ll");                  // ?usize
_ = mem.indexOfScalar(u8, "hello", 'l');
_ = mem.startsWith(u8, "hello", "he");
_ = mem.endsWith(u8, "hello", "lo");
_ = mem.count(u8, "banana", "a");
@memcpy(dest[0..src.len], src);                      // copy (non-overlapping)
@memset(buf, 0);                                     // fill
mem.copyForwards(u8, dest, src);                     // overlapping-safe copy
mem.reverse(u8, &arr_bytes);
mem.sort(i32, &nums, {}, std.sort.asc(i32));         // or std.mem.sortUnstable
_ = mem.max(i32, &nums);
_ = mem.min(i32, &nums);
_ = mem.lessThan(u8, "a", "b");
_ = mem.zeroes(Point);                               // zero-initialized value
mem.swap(i32, &x, &y);
_ = mem.readInt(u32, bytes[0..4], .little);          // endian-aware integer read
mem.writeInt(u32, bytes[0..4], 0xDEADBEEF, .big);