Empty identifier understanding for golang

  • 2020-06-23 00:39:21
  • OfStack

Blank character (blank identifier)

Whitespace may be generated because go does not allow variable declarations but does not use them. Why declare variables when you don't want to use them, replace them with whitespace, which is what you throw away anyway.

We sometimes see golang code like this:


import _ "net/http/pprof"

or


for _, c := range "11234" {
  log.Println(c)
}

or


var _ io.Reader = (* XXX)(nil)  // The global variable 

or


var _ = Suite(&HelloWorldTest{})

In code _ is unique: say variable, but it can be defined multiple times in the same scope; Let's say it's a type. It's not written like that.

So who is it?

The official document actually has a definition and an introduction, and it's called Black Identifier , the Chinese translation is empty identifier. An empty identifier is not a normal variable, but a special treatment provided by the language to avoid naming a variable and to discard a value when assigning a value.

Empty identifier 1 is commonly used in four situations, corresponding to the four sections of code in the above example.

1. Introduce a package to only execute init functions in the package, but this package does not directly reference any variables or functions of the package, use import _ to avoid compilation errors;

2. The function has multiple return values, some of which are ignored. Similar to c++11 std::ignore in std::tie;

3. Compile time check, such as whether a certain type has implemented an interface;

4. If you want to execute a piece of code before init, you can also use init.

Sample blank_identifier go


package main
import "fmt"
func main() {
  var i1 int
  var f1 float32
  i1, _, f1 = ThreeValues()
  fmt.Printf("The int: %d, the float: %f \n", i1, f1)
}
func ThreeValues() (int, int, float32) {
  return 5, 6, 7.5
}

Output results:

[

The int: 5, the float: 7.500000

]

conclusion


Related articles: