Arrays

arrays.zig

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

See also: