gpt4 book ai didi

variables - Go 声明中的 "_,"(下划线逗号)是什么?

转载 作者:IT老高 更新时间:2023-10-28 12:57:36 24 4
gpt4 key购买 nike

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

_, prs := m["example"]

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

prs := m["example"]

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

最佳答案

它避免了必须为返回值声明所有变量。
它被称为 blank identifier .

如:

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

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

(other '_' use case is for import)

由于它会丢弃返回值,因此当您只想检查一个返回值时会很有帮助,如“How to test key existence in a map?”中所示的“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添加 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)

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

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
}

关于variables - Go 声明中的 "_,"(下划线逗号)是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27764421/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com