| ... | ... | @@ -1,41 +1,47 @@ |
| 1 | 1 | const expectEqual = @import("std").testing.expectEqual; |
| 2 | 2 | |
| 3 | 3 | test "for basics" { |
| 4 | | const items = [_]i32{ 4, 5, 3, 4, 0 }; |
| 4 | const items = [_]i32{ 4, 5, 3, -1, 4 }; |
| 5 | 5 | var sum: i32 = 0; |
| 6 | 6 | |
| 7 | 7 | // For loops iterate over slices and arrays. |
| 8 | 8 | for (items) |value| { |
| 9 | 9 | // Break and continue are supported. |
| 10 | | if (value == 0) { |
| 10 | if (value < 0) { |
| 11 | 11 | continue; |
| 12 | 12 | } |
| 13 | 13 | sum += value; |
| 14 | 14 | } |
| 15 | 15 | try expectEqual(16, sum); |
| 16 | 16 | |
| 17 | | // To iterate over a portion of a slice, reslice. |
| 18 | | for (items[0..1]) |value| { |
| 17 | // Use slicing to iterate over a portion of a slice or array. |
| 18 | sum = 0; |
| 19 | for (items[0..2]) |value| { |
| 19 | 20 | sum += value; |
| 20 | 21 | } |
| 21 | | try expectEqual(20, sum); |
| 22 | try expectEqual(9, sum); |
| 23 | } |
| 24 | |
| 25 | test "for ranges" { |
| 26 | const items = [_]u8{1, 2, 3}; |
| 27 | var sum: usize = 0; |
| 22 | 28 | |
| 23 | | // To access the index of iteration, specify a second condition as well |
| 24 | | // as a second capture value. |
| 25 | | var sum2: i32 = 0; |
| 26 | | for (items, 0..) |_, i| { |
| 29 | // To access the index of iteration, specify an unbounded range as the |
| 30 | // second condition, as well as a second capture value. |
| 31 | for (items, 0..) |e, i| { |
| 27 | 32 | try expectEqual(usize, @TypeOf(i)); |
| 28 | | sum2 += @as(i32, @intCast(i)); |
| 33 | sum += i; |
| 34 | try expectEqual(e, i + 1); |
| 29 | 35 | } |
| 30 | | try expectEqual(10, sum2); |
| 36 | try expectEqual(3, sum); // 0 + 1 + 2 |
| 31 | 37 | |
| 32 | | // To iterate over consecutive integers, use the range syntax. |
| 33 | | // Unbounded range is always a compile error. |
| 34 | | var sum3: usize = 0; |
| 38 | // To iterate over consecutive integers, use bounded range syntax. |
| 39 | // A lone unbounded range is a compile error. |
| 40 | sum = 0; |
| 35 | 41 | for (0..5) |i| { |
| 36 | | sum3 += i; |
| 42 | sum += i; |
| 37 | 43 | } |
| 38 | | try expectEqual(10, sum3); |
| 44 | try expectEqual(10, sum); |
| 39 | 45 | } |
| 40 | 46 | |
| 41 | 47 | test "multi object for" { |
| ... | ... | @@ -44,8 +50,8 @@ test "multi object for" { |
| 44 | 50 | var count: usize = 0; |
| 45 | 51 | |
| 46 | 52 | // Iterate over multiple objects. |
| 47 | | // All lengths must be equal at the start of the loop, otherwise detectable |
| 48 | | // illegal behavior occurs. |
| 53 | // All bounded objects must have equal lengths. |
| 54 | // There must be at least one bounded object. |
| 49 | 55 | for (items, items2) |i, j| { |
| 50 | 56 | count += i + j; |
| 51 | 57 | } |