dtbonklcs575884485 2015-11-30 18:36
浏览 222
已采纳

如何在for循环中组合多个赋值和Range

I'm trying to figure out how to (or if it's possible to) combine multiple assignment and ranges in Golang

ex pseudo code of what I'd like to do

files := [2]*os.File{}

for i, _, fileName := 0, range os.Args[1:3] {
  files[i], _ = os.Open(fileName)
}

The idea being I want to have both an iteration counter (i) and the filenames (fileName). I know this can be achieved by using the key from range and some math (key -1), thats not the point of the example.

Edit:

Upon debugging the above example, I learned that i will range 0-1 in that example; Because os.Args[1:2] is a slice and that slice has indexing 0-1 . Therefore I dont need "some math" to properly index the keys.

** EDIT 2: ** This post is also a must read as to why the above [2]*os.File{} is not idiomatic go, instead it should not have a size specified (files := []*os.File{}) so that files is of type slice of *os.File

  • 写回答

2条回答 默认 最新

  • dongyixiu3110 2015-11-30 19:32
    关注

    There are a lot of different issues here. First, range already does what you want. There's no need for even math.

    for i, fileName := range os.Args[1:] {
    

    i will range from 0 to 1 here, just like you want. Ranging over a slice always starts at index 0 (it's relative to the start of the slice). (http://play.golang.org/p/qlVM6Y7yPD)

    Note that os.Args[1:2] is just one element. You probably meant it to be two.

    In any case, this is likely what you really meant:

    http://play.golang.org/p/G4yfkKrEe7

    files := make([]*os.File, 0)
    
    for _, fileName := range os.Args[1:] {
        f, err := os.Open(fileName)
        if err != nil {
            log.Fatalf("Could not open file: %v", err)
        }
        files = append(files, f)
    }
    fmt.Printf("%v
    ", files)
    

    Fixed-length arrays are very uncommon in Go. Generally you want a slice, created with make.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?