| ... | ... | @@ -75,20 +75,22 @@ test "for reference" { |
| 75 | 75 | |
| 76 | 76 | test "for else" { |
| 77 | 77 | // For allows an else attached to it, the same as a while loop. |
| 78 | | const items = [_]?i32{ 3, 4, null, 5 }; |
| 78 | // The else branch is evaluated when the loop completes without a break. |
| 79 | const items = [_]i32{ 3, 4, 5 }; |
| 79 | 80 | |
| 80 | | // For loops can also be used as expressions. |
| 81 | | // Similar to while loops, when you break from a for loop, the else branch is not evaluated. |
| 82 | | var sum: i32 = 0; |
| 83 | 81 | const result = for (items) |value| { |
| 84 | | if (value != null) { |
| 85 | | sum += value.?; |
| 86 | | } |
| 87 | | } else blk: { |
| 88 | | try expectEqual(12, sum); |
| 89 | | break :blk sum; |
| 90 | | }; |
| 91 | | try expectEqual(12, result); |
| 82 | if (value > 10) break value; |
| 83 | } else 0; |
| 84 | |
| 85 | try expectEqual(0, result); |
| 86 | |
| 87 | const more_items = [_]i32{ 3, 4, 11, 5 }; |
| 88 | |
| 89 | const another_result = for (more_items) |value| { |
| 90 | if (value > 10) break value; |
| 91 | } else 0; |
| 92 | |
| 93 | try expectEqual(11, another_result); |
| 92 | 94 | } |
| 93 | 95 | |
| 94 | 96 | // test |