master
  1const expect = @import("std").testing.expect;
  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 expect(sum == 'h' + 'e' + 'l' * 2 + 'o');
 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 expect(some_integers[10] == 10);
 43    try expect(some_integers[99] == 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// ** does repeating patterns
 64const pattern = "ab" ** 3;
 65comptime {
 66    assert(mem.eql(u8, pattern, "ababab"));
 67}
 68
 69// initialize an array to zero
 70const all_zero = [_]u16{0} ** 10;
 71
 72comptime {
 73    assert(all_zero.len == 10);
 74    assert(all_zero[5] == 0);
 75}
 76
 77// use compile-time code to initialize an array
 78var fancy_array = init: {
 79    var initial_value: [10]Point = undefined;
 80    for (&initial_value, 0..) |*pt, i| {
 81        pt.* = Point{
 82            .x = @intCast(i),
 83            .y = @intCast(i * 2),
 84        };
 85    }
 86    break :init initial_value;
 87};
 88const Point = struct {
 89    x: i32,
 90    y: i32,
 91};
 92
 93test "compile-time array initialization" {
 94    try expect(fancy_array[4].x == 4);
 95    try expect(fancy_array[4].y == 8);
 96}
 97
 98// call a function to initialize an array
 99var more_points = [_]Point{makePoint(3)} ** 10;
100fn makePoint(x: i32) Point {
101    return Point{
102        .x = x,
103        .y = x * 2,
104    };
105}
106test "array initialization with function calls" {
107    try expect(more_points[4].x == 3);
108    try expect(more_points[4].y == 6);
109    try expect(more_points.len == 10);
110}
111
112// test