authorgravatar for manlio.perillo@gmail.comManlio Perillo <manlio.perillo@gmail.com> 2023-04-23 20:00:10+02:00
committergravatar for noreply@github.comGitHub <noreply@github.com> 2023-04-23 21:00:10+03:00
log658b4db223c24616a95cdf3bb3226caa23a3b50e
treecdc884e807b1e3d892739f48df7fb658d6ae1508
parent253eb72c1489604549ff35e1f9f32844f1bc31b5
signaturebadge-question-mark Signed by PGP key 4AEE18F83AFDEB23

langref: improve for loop documentation

- Add an example of iterating over consecutive integers using the range syntax - Add an example of iterating over multiple objects - Update the "nested break" and "nested continue" tests to use the range syntax, instead of a temporary array

1 files changed, 27 insertions(+), 4 deletions(-)

doc/langref.html.in+27-4
...@@ -4667,6 +4667,29 @@ test "for basics" {...@@ -4667,6 +4667,29 @@ test "for basics" {
4667 sum2 += @intCast(i32, i);4667 sum2 += @intCast(i32, i);
4668 }4668 }
4669 try expect(sum2 == 10);4669 try expect(sum2 == 10);
4670
4671 // To iterate over consecutive integers, use the range syntax.
4672 // Unbounded range is always a compile error.
4673 var sum3 : usize = 0;
4674 for (0..5) |i| {
4675 sum3 += i;
4676 }
4677 try expect(sum3 == 10);
4678}
4679
4680test "multi object for" {
4681 const items = [_]usize{ 1, 2, 3 };
4682 const items2 = [_]usize{ 4, 5, 6 };
4683 var count: usize = 0;
4684
4685 // Iterate over multiple objects.
4686 // All lengths must be equal at the start of the loop, otherwise detectable
4687 // illegal behavior occurs.
4688 for (items, items2) |i, j| {
4689 count += i + j;
4690 }
4691
4692 try expect(count == 21);
4670}4693}
46714694
4672test "for reference" {4695test "for reference" {
...@@ -4710,8 +4733,8 @@ const expect = std.testing.expect;...@@ -4710,8 +4733,8 @@ const expect = std.testing.expect;
47104733
4711test "nested break" {4734test "nested break" {
4712 var count: usize = 0;4735 var count: usize = 0;
4713 outer: for ([_]i32{ 1, 2, 3, 4, 5 }) |_| {4736 outer: for (1..6) |_| {
4714 for ([_]i32{ 1, 2, 3, 4, 5 }) |_| {4737 for (1..6) |_| {
4715 count += 1;4738 count += 1;
4716 break :outer;4739 break :outer;
4717 }4740 }
...@@ -4721,8 +4744,8 @@ test "nested break" {...@@ -4721,8 +4744,8 @@ test "nested break" {
47214744
4722test "nested continue" {4745test "nested continue" {
4723 var count: usize = 0;4746 var count: usize = 0;
4724 outer: for ([_]i32{ 1, 2, 3, 4, 5, 6, 7, 8 }) |_| {4747 outer: for (1..9) |_| {
4725 for ([_]i32{ 1, 2, 3, 4, 5 }) |_| {4748 for (1..6) |_| {
4726 count += 1;4749 count += 1;
4727 continue :outer;4750 continue :outer;
4728 }4751 }