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

huangapple go评论91阅读模式
英文:

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

问题

我可以帮你翻译这段内容:

我不太理解这种变量声明的含义:

_, prs := m["example"]

"_, "这部分是在做什么?为什么他们要这样声明变量,而不是像下面这样:

prs := m["example"]

(我在Go by Example: Maps中找到了这个例子)

英文:

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)

答案1

得分: 155

它避免了声明所有返回值的变量。这被称为“空白标识符”。

例如:

_, y, _ := coord(p)  // coord() 返回三个值;只对 y 坐标感兴趣

这样,你就不需要声明一个不会使用的变量:Go 不允许这样做。相反,使用“_”来忽略该变量。

(另一个“_”的用例是用于导入)

由于它丢弃了返回值,当你只想检查其中一个返回值时,它非常有用,比如在“如何在映射中测试键是否存在?”中所示的“Effective Go, map”:

_, present := timeZone[tz]

为了测试映射中的存在性而不用担心实际值,你可以使用空白标识符,一个简单的下划线(_)。
空白标识符可以被赋予或声明为任何类型的任何值,该值会被无害地丢弃。
为了测试映射中的存在性,使用空白标识符来代替通常用于值的变量。

正如 Jsor评论中 补充的:

“普遍接受的标准”是将成员测试变量称为“ok”(检查通道读取是否有效也是如此)

这使你可以将其与测试结合使用:

if _, err := os.Stat(path); os.IsNotExist(err) {
	fmt.Printf("%s 不存在\n", path)
}

你也可以在循环中找到它:

如果你只需要范围中的第二个项目(值),可以使用空白标识符(下划线)来丢弃第一个:

sum := 0
for _, value := range array {
    sum += value
}
英文:

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

That way, you don't have to declare a variable you won't use: Go would not allow it. Instead, use '_' to ignore said variable.

(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\n", 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
}

答案2

得分: 79

Go编译器不允许你创建未使用的变量。

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

上述代码将返回一个错误信息:"i被声明但未使用"。

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

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

The Go compiler won't allow you to create variables that you never use.

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

The above code will return an error message "i declared and not used".

Since we don't use i inside of our loop we need to change it to this:

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

答案3

得分: 5

空白标识符可以在语法要求变量名但程序逻辑不需要的情况下使用,例如在我们只需要元素值时,可以丢弃不需要的循环索引。

摘自:

《Go语言程序设计》(Addison-Wesley专业计算系列)

Brian W. Kernighan

此内容可能受版权保护。

英文:

>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.

Excerpt From:

The Go Programming Language (Addison-Wesley Professional Computing Series)

Brian W. Kernighan

This material may be protected by copyright.

答案4

得分: 4

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

在这里,被丢弃的是 example 键的值。第二行代码会丢弃 presence 布尔值,并将该值存储在 prs 中。
因此,如果只想检查映射中是否存在某个键,可以丢弃该值。这可以用来将映射用作集合。

英文:

_ is the blank identifier. Meaning the value it should be assigned is discarded.

Here it is the value of example key that is discarded. The second line of code would discard the presence boolean and store the value in prs.
So to only check the presence in the map, you can discard the value. This can be used to use a map as a set.

答案5

得分: 4

未使用变量的一个很好的用例是当你只需要部分输出时。在下面的示例中,我们只需要打印值(州的人口)。

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

The great use case for the unused variable is the situation when you only need a partial output. In the example below we only need to print the value (state population).

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

答案6

得分: 2

它被称为空白标识符,它在以下情况下有用:当你希望丢弃即将返回的值并不引用它时。

一些使用空白标识符的场景包括:

  • 函数返回一个值,但你不打算在将来使用它。
  • 你想要进行迭代,并且需要一个你不会使用的 i 值。
英文:

It is called the blank identifier and it helps in cases where you wish to discard the value that is going to be returned and not reference it

Some places where we use it:

  • A function returns a value and you don't intend to use it in the
    future
  • You want to iterate and need an i value that you will not be
    using

答案7

得分: 2

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

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

因此,在这种情况下我们需要使用 _

此外,当你不希望将函数的返回值用于未来时,也可以使用 _

英文:

Basically, _, known as the blank identifier. In GO we can't have variables that are not being used.

As an instance when you iterating through an array if you are using value := range you don't want a i value for iterating. But if you omit the i value it will return an error. But if you declare i and didn't use it, it will also return an error.

Therefore, that is the place where we have to use _,.

Also it is used when you don't want a function's return value in the future.

答案8

得分: 2

在Golang中,下划线(_)被称为Blank Identifier(空白标识符)。标识符是程序组件的用户定义名称,用于标识目的。Golang具有一种特殊功能,可以使用Blank Identifier来定义和使用未使用的变量。未使用的变量是指用户在整个程序中定义但从未使用过的变量。

当Go编译器遇到声明但未使用的变量时,会抛出错误。现在我们可以简单地使用空白标识符而不声明任何变量。

以下是修正上述程序的使用空白标识符的示例:

// 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

使用空白标识符可以让编译器忽略特定变量的声明但未使用错误。

英文:

_(underscore) in Golang is known as the Blank Identifier. Identifiers are the user-defined name of the program components used for the identification purpose. Golang has a special feature to define and use the unused variable using Blank Identifier. Unused variables are those variables that are defined by the user throughout the program but he/she never makes use of these variables.
Go compiler throws an error whenever it encounters a variable declared but not used. Now we can simply use the blank identifier and not declare any variable at all.

   // 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
}

Output

./prog.go:15:7: div declared and not used

Let’s make use of the Blank identifier to correct the above program. In place of div identifier just use the _ (underscore). It allows the compiler to ignore declared and not used error for that particular variable.

    // 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
}

Output

105 x 7 =  735

答案9

得分: 1

“在Golang中,不允许存在未使用的变量。如果你之前使用其他编程语言,可能会感到有些难以适应。但这样可以使代码更加清晰。因此,通过使用_,我们表明我们知道在那里有一个变量,但我们不想使用它,并告诉编译器不要对此发出警告。”

英文:

> An unused variable is not allowed in Golang

If you were coming from other programming languages this might feel bit difficult to get used to this. But this results in more cleaner code. So by using a _ we are saying we know there is a variable there but we don't want to use it and telling the compiler that does not complain me about it. What is "_," (underscore comma) in a Go declaration?

huangapple
  • 本文由 发表于 2015年1月4日 18:07:31
  • 转载请务必保留本文链接:https://go.coder-hub.com/27764421.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定