Skip to content

Commit 5b4759b

Browse files
raindevalexrp
authored andcommitted
Clarify the multidimensional array example
Use a rectangular matrix instead of a square one to distinguish rows and columns more clearly. Extend the example with row access.
1 parent b350049 commit 5b4759b

File tree

1 file changed

+13
-9
lines changed

1 file changed

+13
-9
lines changed

doc/langref/test_multidimensional_arrays.zig

+13-9
Original file line numberDiff line numberDiff line change
@@ -1,27 +1,31 @@
11
const std = @import("std");
22
const expect = std.testing.expect;
3+
const expectEqual = std.testing.expectEqual;
34

4-
const mat4x4 = [4][4]f32{
5-
[_]f32{ 1.0, 0.0, 0.0, 0.0 },
6-
[_]f32{ 0.0, 1.0, 0.0, 1.0 },
7-
[_]f32{ 0.0, 0.0, 1.0, 0.0 },
8-
[_]f32{ 0.0, 0.0, 0.0, 1.0 },
5+
const mat4x5 = [4][5]f32{
6+
[_]f32{ 1.0, 0.0, 0.0, 0.0, 0.0 },
7+
[_]f32{ 0.0, 1.0, 0.0, 1.0, 0.0 },
8+
[_]f32{ 0.0, 0.0, 1.0, 0.0, 0.0 },
9+
[_]f32{ 0.0, 0.0, 0.0, 1.0, 9.9 },
910
};
1011
test "multidimensional arrays" {
12+
// mat4x5 itself is a one-dimensional array of arrays.
13+
try expectEqual(mat4x5[1], [_]f32{ 0.0, 1.0, 0.0, 1.0, 0.0 });
14+
1115
// Access the 2D array by indexing the outer array, and then the inner array.
12-
try expect(mat4x4[1][1] == 1.0);
16+
try expect(mat4x5[3][4] == 9.9);
1317

1418
// Here we iterate with for loops.
15-
for (mat4x4, 0..) |row, row_index| {
19+
for (mat4x5, 0..) |row, row_index| {
1620
for (row, 0..) |cell, column_index| {
1721
if (row_index == column_index) {
1822
try expect(cell == 1.0);
1923
}
2024
}
2125
}
2226

23-
// initialize a multidimensional array to zeros
24-
const all_zero: [4][4]f32 = .{.{0} ** 4} ** 4;
27+
// Initialize a multidimensional array to zeros.
28+
const all_zero: [4][5]f32 = .{.{0} ** 5} ** 4;
2529
try expect(all_zero[0][0] == 0);
2630
}
2731

0 commit comments

Comments
 (0)