2017-01-03 13:59 阅读 55


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?

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享

1条回答 默认 最新

  • 已采纳
    dqtu14636 dqtu14636 2017-01-03 14:11

    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 {
        s += fmt.Sprintf("%d: %s", index, arg)
    点赞 评论 复制链接分享