I have seen a couple of people complaining about the for-loop, along the lines of "why should we have to say i = 0; i < len; i++
in this day and age?".
I disagree, I like the for construct. You can use the long version if you wish, but the idiomatic Go is
var a = []int{1,2,3};
for i, v := range a {
fmt.Println(i, v);
}
The for .. range
construct loops over all the elements and supplies two values - the index i
and the value v
.
range
also works on maps and channels.
Still, if you dislike for
in any form, you can define each
, map
etc. in a few lines:
type IntArr []int
// 'each' takes a function argument.
// The function must accept two ints, the index and value,
// and will be called on each element in turn.
func (a IntArr) each(fn func(index, value int)) {
for i, v := range a { fn(i, v); }
}
func main() {
var a = IntArr([]int{2,0,0,9}); // create int slice and cast to IntArr
var fnPrint = func (i, v int) {
fmt.Println(i, ":", v);
}; // create a function
a.each(fnPrint); // call on each element
}
prints
0 : 2
1 : 0
2 : 0
3 : 9
I'm starting to like Go a lot :)