dongxia026531 2017-01-03 13:59
浏览 60
已采纳

在切片上进行循环索引以获取范围

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 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 {
            continue
        }
        s += fmt.Sprintf("%d: %s", index, arg)
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 按键修改电子时钟,C51单片机
  • ¥60 Java中实现如何实现张量类,并用于图像处理(不运用其他科学计算库和图像处理库))
  • ¥20 5037端口被adb自己占了
  • ¥15 python:excel数据写入多个对应word文档
  • ¥60 全一数分解素因子和素数循环节位数
  • ¥15 ffmpeg如何安装到虚拟环境
  • ¥188 寻找能做王者评分提取的
  • ¥15 matlab用simulink求解一个二阶微分方程,要求截图
  • ¥30 乘子法解约束最优化问题的matlab代码文件,最好有matlab代码文件
  • ¥15 写论文,需要数据支撑