duanliang4009 2015-01-04 10:07
浏览 453
已采纳

Go声明中的“ _”(下划线逗号)是什么?

And I can't seem to understand this kind of variable declaration:

_, prs := m["example"]

What exactly is "_," doing and why have they declared a variable like this instead of

prs := m["example"]

(I found it as part of Go by Example: Maps)

  • 写回答

7条回答 默认 最新

  • dongsetan3216 2015-01-04 10:09
    关注

    It avoids having to declare all the variables for the returns values.
    It is called the blank identifier.

    As in:

    _, y, _ := coord(p)  // coord() returns three values; only interested in y coordinate
    

    (the other '_' use case is for import)

    Since it discards the return value, it is helpful when you want to check only one of the returned values, as in "How to test key existence in a map?" shown in "Effective Go, map":

    _, present := timeZone[tz]
    

    To test for presence in the map without worrying about the actual value, you can use the blank identifier, a simple underscore (_).
    The blank identifier can be assigned or declared with any value of any type, with the value discarded harmlessly.
    For testing presence in a map, use the blank identifier in place of the usual variable for the value.

    As Jsor adds in the comments:

    "generally accepted standard" is to call the membership test variables "ok" (same for checking if a channel read was valid or not)

    That allows you to combine it with test:

    if _, err := os.Stat(path); os.IsNotExist(err) {
        fmt.Printf("%s does not exist
    ", path)
    }
    

    You would find it also in loop:

    If you only need the second item in the range (the value), use the blank identifier, an underscore, to discard the first:

    sum := 0
    for _, value := range array {
        sum += value
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(6条)

报告相同问题?

悬赏问题

  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码