Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Go loop indices for range on slice

I have a fairly simple question, but can't find answer anywhere. I'm iterating over a range of slices, like this:

for index, arg := range os.Args[1:] {
    s += fmt.Sprintf("%d: %s", index, arg)
}

As I understand range iterates over a slice, and index is created from range, and it's zero-based. I get the output:

0: argument_1
1: argument_2
// etc.

But it's not what I expect - I need range to preserve indices of that slice, so my output looks like this:

1: argument_1
2: argument_2
// etc.

The most obvious way to achieve this is to add shift on index in loop:

shift := 1
for index, arg := range os.Args[shift:] {
    index += shift
    s += fmt.Sprintf("%d: %s", index, arg)
}

But I was wondering, is there more "Go-ish" way to do this, and also, how to preserve indices when creating a slice in Go like this?

like image 802
Damaged Organic Avatar asked Oct 18 '22 19:10

Damaged Organic


1 Answers

There is nothing wrong with your original code, when you are doing os.Args[1:] you are creating a new slice which like any slice starts at index 0.
It's a matter of style (and performance) but you could also do this:

for index, arg := range os.Args {
    if index < 1 {
        continue
    }
    s += fmt.Sprintf("%d: %s", index, arg)
}
like image 167
Franck Jeannin Avatar answered Nov 14 '22 00:11

Franck Jeannin