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条)

报告相同问题?

悬赏问题

  • ¥15 关于#python#的问题:求帮写python代码
  • ¥15 LiBeAs的带隙等于0.997eV,计算阴离子的N和P
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
  • ¥15 来真人,不要ai!matlab有关常微分方程的问题求解决,
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误
  • ¥199 rust编程架构设计的方案 有偿
  • ¥15 回答4f系统的像差计算
  • ¥15 java如何提取出pdf里的文字?