英文:
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 < 1 {
continue
}
s += fmt.Sprintf("%d: %s", index, arg)
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论