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" {
// Here’s three ways to define an array of five
// elements of type 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" {
// We can use @splat to initialize all elements with
// the same value.
const a: [6]u64 = @splat(0);
try expectEqual([6]u64{ 0, 0, 0, 0, 0, 0 }, a);
}
test "multi-dimensional arrays" {
// Multidimensional arrays can be created by nesting
// 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
All 5 tests passed.
Next example: Slices.