Arrays

An array is a sequence of values of the same type with fixed length:

const std = @import("std");
const expect = std.testing.expect;
const expectEqual = std.testing.expectEqual;

test "array literals" {
    // Three ways to define an array of five u64:
    const a = [5]u64{ 1, 2, 3, 4, 5 };
    const b = [_]u64{ 1, 2, 3, 4, 5 };
    const c: [5]u64 = .{ 1, 2, 3, 4, 5 };

    try expect(@TypeOf(a) == [5]u64);
    try expect(@TypeOf(b) == [5]u64);
    try expect(@TypeOf(c) == [5]u64);

    // .len gives us the length (number of elements).
    try expect(a.len == 5);
}

test "array indexing" {
    // Use […] to get or set a value.
    var a = [5]u64{ 1, 2, 3, 4, 5 };
    try expect(a[4] == 5);

    a[4] *= 2;
    try expect(a[4] == 10);
}

test "++ operator" {
    // The ++ operator concatenates two arrays.
    const a = [_]u64{ 1, 2 };
    const b = [_]u64{ 3, 4 };
    const c = a ++ b;
    try expectEqual([4]u64{ 1, 2, 3, 4 }, c);
}

test "@splat builtin function" {
    // Use @splat to initialize all elements:
    const a: [6]u64 = @splat(0);
    try expectEqual([6]u64{ 0, 0, 0, 0, 0, 0 }, a);
}

test "multi-dimensional arrays" {
    const matrix: [3][3]f64 = .{
        .{ 1, 0, 4 },
        .{ 0, 1, 5 },
        .{ 0, 0, 1 },
    };
    try expect(matrix[1][2] == 5); // row 1, col 2
}
$ zig test arrays.zig
1/5 arrays.test.array literals...OK
2/5 arrays.test.array indexing...OK
3/5 arrays.test.++ operator...OK
4/5 arrays.test.@splat builtin function...OK
5/5 arrays.test.multi-dimensional arrays...OK
All 5 tests passed.

Next example: Slices.