| ... | @@ -75,20 +75,22 @@ test "for reference" { | ... | @@ -75,20 +75,22 @@ test "for reference" { |
| 75 | | 75 | |
| 76 | test "for else" { | 76 | test "for else" { |
| 77 | // For allows an else attached to it, the same as a while loop. | 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 | const result = for (items) |value| { | 81 | const result = for (items) |value| { |
| 84 | if (value != null) { | 82 | if (value > 10) break value; |
| 85 | sum += value.?; | 83 | } else 0; |
| 86 | } | 84 | |
| 87 | } else blk: { | 85 | try expectEqual(0, result); |
| 88 | try expectEqual(12, sum); | 86 | |
| 89 | break :blk sum; | 87 | const more_items = [_]i32{ 3, 4, 11, 5 }; |
| 90 | }; | 88 | |
| 91 | try expectEqual(12, result); | 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 | // test | 96 | // test |