3 ms·
> Well, yeah, but if you want to iterate over integer ranges, don't you use the for ;; {} form? (If not why is that form even there?) for range does iterate ov
by laumars 11y ago
> Well, yeah, but if you want to iterate over integer ranges, don't you use the for ;; {} form? (If not why is that form even there?)
for range does iterate over integer arrays / slices. The reason the C-style for loop exists is because sometimes you don't want to iterate the entire stack. eg
// iterate half the stack:
for i := 0; i < len(slice) / 2; i++ {}
// iterate with a stepping:
for i := 0; i < len(slice); i+=2 {}
// iterate from a different starting position:
for i := 5; i < len(slice); i++ {}
// reverse iteration:
for i := len(slice)-1; i>=0; i-- {}
- infogulch 11y agoSlicing is free and can be done inline, so your first and third examples can be changed to the range syntax: // iterate half the stack: for i := range slice[:len(slice)/2] {} // iterate from a different starting position: for i := range slice[5:] {} That still leaves stepping and reverse, but I've found those are relatively rare, especially compared to the other two.
- laumars 11y agoOoops, just seen this comment. Yes, you're right, your slice techniques do make a lot more sense than my examples.