在切片上使用range的循环索引

huangapple go评论84阅读模式
英文:

Go loop indices for range on slice

问题

我有一个相当简单的问题,但是找不到答案。我正在迭代一系列的切片,像这样:

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

据我理解,range会遍历一个切片,index是从range中创建的,并且它是从零开始的。我得到的输出是:

0: argument_1
1: argument_2
// 等等

但这不是我期望的结果 - 我希望range保留该切片的索引,所以我的输出应该是这样的:

1: argument_1
2: argument_2
// 等等

实现这个的最直观的方法是在循环中添加索引的偏移量shift

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

但我想知道,是否有更符合Go语言风格的方法来实现这个,还有,在Go中如何在创建切片时保留索引?

英文:

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

得分: 7

你的原始代码没有问题,当你使用os.Args[1:]时,你创建了一个新的切片,就像任何切片一样,从索引0开始。这是一种风格(和性能)的问题,但你也可以这样做:

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

这段代码的作用与你的原始代码相同。

英文:

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.<br>
It's a matter of style (and performance) but you could also do this:

for index, arg := range os.Args {
	if index &lt; 1 {
		continue
	}
	s += fmt.Sprintf(&quot;%d: %s&quot;, index, arg)
}

huangapple
  • 本文由 发表于 2017年1月3日 21:59:17
  • 转载请务必保留本文链接:https://go.coder-hub.com/41445216.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定