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

What is "_," (underscore comma) in a Go declaration?

而且我似乎无法理解这种变量声明:

_, prs := m["example"]

_,”到底在做什么,为什么他们声明这样的变量而不是

prs := m["example"]

(我发现它是 Go by Example: Maps 的一部分)

它避免了为 returns 值声明所有变量。
它被称为 blank identifier.

如:

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

这样一来,您就不必声明您不会使用的变量:Go 不允许这样做。相反,使用“_”忽略所述变量。

(other '_' use case is for import)

因为它丢弃了 return 值,所以当您只想检查一个 returned 值时,它会很有帮助,如 "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.

作为Jsor adds :

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

这允许您将它与测试结合起来:

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

你会发现它也在循环中:

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
}

_ 是空白标识符。意味着它应该分配的值被丢弃。

这里是丢弃的example键的值。第二行代码将丢弃 presence 布尔值并将值存储在 prs.
中 所以只检查地图中的存在,您可以丢弃该值。这个可以用来把一张图当作一个集合来使用。

Go 编译器不允许您创建您从不使用的变量。

for i, value := range x {
   total += value
}

上面的代码会return一个错误信息"i declared and not used"。

由于我们不在循环中使用 i 我们需要将其更改为:

for _, value := range x {
   total += value
}

它被称为空白标识符,在您希望丢弃要返回的值而不引用它的情况下它会有所帮助

我们使用它的一些地方:

  • 一个函数 returns 一个值并且您不打算在 未来
  • 您想迭代并需要一个您不会的 i 值 使用

The blank identifier may be used whenever syntax requires a variable name but program logic does not, for instance to discard an unwanted loop index when we require only the element value.

摘自:

Go 编程语言(Addison-Wesley 专业计算系列)

Brian W. Kernighan

此 material 可能受版权保护。

An unused variable is not allowed in Golang

如果您以前使用过其他编程语言,可能会觉得有点难以适应。但这会产生更简洁的代码。所以通过使用 _ 我们是说我们知道那里有一个变量但我们不想使用它并告诉编译器不要抱怨我。 :)

基本上,_,被称为空白标识符。在 GO 中,我们不能有未使用的变量。

例如,当您使用 value := range 遍历数组时,您不需要 i 值用于迭代。但是,如果您省略 i 值,它将 return 出错。但是如果你声明了 i 而没有使用它,它也会 return 一个错误。

所以,那就是我们不得不用到的地方_,

当您将来不想要某个函数的 return 值时也可以使用它。

未使用变量的最佳用例是您只需要部分输出的情况。在下面的示例中,我们只需要打印值(州人口)。

package main
import (
    "fmt"
)
func main() {
          statePopulations := map[string]int{
          "California": 39250017,
          "Texas":      27862596,
          "Florida":    20612439,
          }
          for _, v := range statePopulations {
          fmt.Println(v)
    }
}