我好像无法理解这种变量声明:
_, prs := m["example"]
"
_,
" 到底是做什么的,为什么他们会像这样声明变量而不是...prs := m["example"]
(我在 Go by Example: Maps 中发现了它。)
我好像无法理解这种变量声明:
_, prs := m["example"]
_,
" 到底是做什么的,为什么他们会像这样声明变量而不是...prs := m["example"]
如下:
_, y, _ := coord(p) // coord() returns three values; only interested in y coordinate
_
'用例是用于导入)_, present := timeZone[tz]
_
)。if _, err := os.Stat(path); os.IsNotExist(err) {
fmt.Printf("%s does not exist\n", path)
}
sum := 0
for _, value := range array {
sum += value
}
Go编译器不允许您创建从未使用过的变量。
for i, value := range x {
total += value
}
上述代码将返回一个错误信息 "i declared and not used"。
由于我们在循环内部没有使用 i,所以需要将其更改为以下内容:
for _, value := range x {
total += value
}
_
是空白标识符,意思是应该将其分配的值丢弃。
在这里,应该被分配的值是example
键的值。第二行代码会丢弃存在布尔值,并将该值存储在prs
中。
因此,只需检查地图中是否存在就可以丢弃值。这可以用于将地图用作集合。
package main
import (
"fmt"
)
func main() {
statePopulations := map[string]int{
"California": 39250017,
"Texas": 27862596,
"Florida": 20612439,
}
for _, v := range statePopulations {
fmt.Println(v)
}
}
Golang中的_(下划线)被称为Blank Identifier。标识符是程序组件的用户定义名称,用于识别目的。 Golang有一个特殊功能,可以使用Blank Identifier定义和使用未使用的变量。 未使用的变量是指用户在整个程序中定义但从未使用过的变量。 当Go编译器遇到声明但未使用的变量时会抛出错误。现在我们可以简单地使用空白标识符而不声明任何变量。
// Golang program to show the compiler
// throws an error if a variable is
// declared but not used
package main
import "fmt"
// Main function
func main() {
// calling the function
// function returns two values which are
// assigned to mul and div identifier
mul, div := mul_div(105, 7)
// only using the mul variable
// compiler will give an error
fmt.Println("105 x 7 = ", mul)
}
// function returning two
// values of integer type
func mul_div(n1 int, n2 int) (int, int) {
// returning the values
return n1 * n2, n1 / n2
}
输出
./prog.go:15:7: div declared and not used
让我们使用空白标识符来修正上面的程序。只需使用 _ (下划线) 替换 div 标识符即可。它允许编译器忽略该特定变量的已声明但未使用的错误。
// Golang program to the use of Blank identifier
package main
import "fmt"
// Main function
func main() {
// calling the function
// function returns two values which are
// assigned to mul and blank identifier
mul, _ := mul_div(105, 7)
// only using the mul variable
fmt.Println("105 x 7 = ", mul)
}
// function returning two
// values of integer type
func mul_div(n1 int, n2 int) (int, int) {
// returning the values
return n1 * n2, n1 / n2
}
输出
105 x 7 = 735
_
被称为空白标识符。在GO中,我们不能有未使用的变量。 _
的地方。它被称为空白标识符,并且在您希望丢弃将要返回的值并不引用它的情况下有所帮助。
我们使用它的一些场景:
在Golang中不允许使用未使用的变量
如果你来自其他编程语言,可能会感到有些困难。但这会导致更加清晰的代码。因此,通过使用 _
,我们表明知道那里有一个变量,但我们不想使用它,并告诉编译器不要对此发出投诉。 :)
prs
可能代表 "present"。你的示例代码正在检查m
映射中是否存在或不存在"example"
条目。 - dyoo