13

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
}

2 Answers 2

17

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]
}

?

Sign up to request clarification or add additional context in comments.

3 Comments

So in this case Will I have the sequence v[1], v[4], v[8], ...?
No, you'll have to not use range for that case.
I guess @angry_gopher wanted a way to specify what he wants to do and leave how it's done to the library. Mostly hangover from languages with abstraction. Go doesn't need abstractions.
0

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.

1 Comment

I must add that the lack of abstraction in Go is refreshing after years of doing C++, Java, Ruby - none of which are both simple and fast. :D

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.