1const expectEqual = @import("std").testing.expectEqual;
2const assert = @import("std").debug.assert;
3const mem = @import("std").mem;
4
5// array literal
6const message = [_]u8{ 'h', 'e', 'l', 'l', 'o' };
7
8// alternative initialization using result location
9const alt_message: [5]u8 = .{ 'h', 'e', 'l', 'l', 'o' };
10
11comptime {
12 assert(mem.eql(u8, &message, &alt_message));
13}
14
15// get the size of an array
16comptime {
17 assert(message.len == 5);
18}
19
20// A string literal is a single-item pointer to an array.
21const same_message = "hello";
22
23comptime {
24 assert(mem.eql(u8, &message, same_message));
25}
26
27test "iterate over an array" {
28 var sum: usize = 0;
29 for (message) |byte| {
30 sum += byte;
31 }
32 try expectEqual('h' + 'e' + 'l' * 2 + 'o', sum);
33}
34
35// modifiable array
36var some_integers: [100]i32 = undefined;
37
38test "modify an array" {
39 for (&some_integers, 0..) |*item, i| {
40 item.* = @intCast(i);
41 }
42 try expectEqual(10, some_integers[10]);
43 try expectEqual(99, some_integers[99]);
44}
45
46// array concatenation works if the values are known
47// at compile time
48const part_one = [_]i32{ 1, 2, 3, 4 };
49const part_two = [_]i32{ 5, 6, 7, 8 };
50const all_of_it = part_one ++ part_two;
51comptime {
52 assert(mem.eql(i32, &all_of_it, &[_]i32{ 1, 2, 3, 4, 5, 6, 7, 8 }));
53}
54
55// remember that string literals are arrays
56const hello = "hello";
57const world = "world";
58const hello_world = hello ++ " " ++ world;
59comptime {
60 assert(mem.eql(u8, hello_world, "hello world"));
61}
62
63// initialize an array to zero
64const all_zero: [10]u16 = @splat(0);
65
66comptime {
67 assert(all_zero.len == 10);
68 assert(all_zero[5] == 0);
69}
70
71// use compile-time code to initialize an array
72var fancy_array = init: {
73 var initial_value: [10]Point = undefined;
74 for (&initial_value, 0..) |*pt, i| {
75 pt.* = Point{
76 .x = @intCast(i),
77 .y = @intCast(i * 2),
78 };
79 }
80 break :init initial_value;
81};
82const Point = struct {
83 x: i32,
84 y: i32,
85};
86
87test "compile-time array initialization" {
88 try expectEqual(4, fancy_array[4].x);
89 try expectEqual(8, fancy_array[4].y);
90}
91
92// call a function to initialize an array
93var more_points: [10]Point = @splat(makePoint(3));
94fn makePoint(x: i32) Point {
95 return Point{
96 .x = x,
97 .y = x * 2,
98 };
99}
100test "array initialization with function calls" {
101 try expectEqual(3, more_points[4].x);
102 try expectEqual(6, more_points[4].y);
103 try expectEqual(10, more_points.len);
104}
105
106// test