Reputation: 1725
Is it possible to iterate over array indices in Go language and choose not all indices but throw some period (1, 2, 3 for instance.
For example,
for i, v := range array {
//do something with i,v
}
iterates over all indices in the array
What I want to know is there any chance to have something like that
for i:=1, v := range array {
//do something with i,v
i += 4
}
Upvotes: 13
Views: 22924
Reputation: 2390
You're looking for an abstraction that does not exist in Golang. Go is "simple" by design. Of course simple itself is a very relative and subjective term. For example, the following would be simple to some:
// This is not real Go code
for index, value := range(array, stride = 4, start = 1) {
...
}
That's because it tells the compiler what to do, not how to do it - definitive abstraction - the how could change without the what changing. But the how is abstracted. Precisely for that reason, some others would prefer:
// This *is* real Go code
start := 1 // we start not at 0 but at one, just for fun
stride := 4 // we skip 3 between this and the next one of interest
for i: = start; i < len(array); i += stride {
...
}
This code tells you how something is being done, and as a side-effect, you ought to understand what's being done. Little abstraction - but that's an engineering trade-off for being both somewhat fast, and somewhat simple. Most of Go's engineering trade-offs err on the side of simplicity and speed.
Go does let you build such an abstraction though, with a little effort.
Upvotes: 0
Reputation: 13171
What's wrong with
i := 1
for _, v := range array {
// do something
i += 4
}
if you want i-values other than indices, or if you want to skip the indices,
for i := 1; i < len(array); i += 4 {
v := array[i]
}
?
Upvotes: 17