const expect = @import("std").testing.expect; // Slices can be thought of many-item pointers (`[*]T`) with a length (usize). These use the syntax `[]T`. // Slices are easier to use safely and more convinient than many-item pointers, // as they store the valid length of the buffer with them. // Slices are sometimes referred to as "fat pointers" as they're typically double the size of a normal pointer. // Slices are the most common way to pass around buffers in Zig. // * COMMING FROM GO? // Slicing in Zig is similar to slicing in Go, but you replace array[start:end] with array[start..end]. // Moreover, in Go, there is no explicit ownership or memory management, meaning that slices point to memory owned by the garbage collector. However in Zig, slices point to manually-managed memory; slices are not tied to memory allocation. This has important implications: // - The validity and lifetime of the backing memory is in the hands of the programmer. // - Zig slices do not have a Cap field, as they do not resize. // For a resizeable/appendable buffer with ownership, have a look at ArrayList. fn total(values: []const u8) usize { var sum: usize = 0; for (values) |v| sum += v; return sum; } test "slices" { const array = [_]u8{ 1, 2, 3, 4, 5 }; const slice = array[0..3]; try expect(total(slice) == 6); } test "slices 2" { const array = [_]u8{ 1, 2, 3, 4, 5 }; const slice = array[0..3]; try expect(@TypeOf(slice) == *const [3]u8); } test "slices 3" { var array = [_]u8{ 1, 2, 3, 4, 5 }; const slice = array[0..]; _ = slice; }