Description
background
I have found that over a sufficiently large sample, c style for loops, for v := 0; v < 25; v++ {}
, can introduce iterator and comparator bugs. As such I prefer for range [N]struct{}{} {}
, or for range make([]struct{}, N) {}
for N
that is not const
, as suggested in #36308 (comment). Unfortunately may people have found this syntax confusing, so I have taken to using iter.N
, which uses the make
form above, cleans up the syntax, and has a godoc explaining what is going on. But @bradfitz "encourage[s] [people] not to depend on this" and calls it out as "not ideomatic", despite the comment above. As such, I would like to have a discussion about including this to the stdlib.
impl
package math
// Iter returns a slice of n 0-sized elements, suitable for ranging over.
//
// For example:
//
// for i := range math.Iter(10) {
// fmt.Println(i)
// }
//
// ... will print 0 to 9, inclusive.
//
// It does not cause any allocations.
func Iter(n int) []struct{} { return make([]struct{}, n) }
alternatives
nop
We can always do nothing, but I think this syntax is reasonable and improves safety and readability of trivial loops. Clearly we still need the c for syntax for non-trivial cases.
inline
If desired, this could be implemented in a way that the compiler more fully inlines it, especially in cases where the index is unused.
names
I am happy to have this be named something different or live in a different package. math
seemed like a decent fit, since there is no numbers
, ints
, or iter
package, and I did not want the stutter of for range math.Range(10) {}
, but it would clearly indicate where it was intended to be used.