SoFunction
Updated on 2025-03-03

Golang's empty identifier understanding

blank identifier

The generation of whitespace characters may be because go does not allow variables to be declared but not used. Since you don't want to use it, why bother declaring a variable? Then replace the variable with a blank sign. Anyway, the blank sign is used to discard it.

Sometimes we see golang code like this:

import _ "net/http/pprof"

or

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

or

var _  = (* XXX)(nil)  //Global variables

or

var _ = Suite(&HelloWorldTest{})

It looks very unique in the code: it is called a variable, but it can be defined multiple times in the same scope; it is called a type, but it is not the same in writing.

So who is it sacred?

In fact, the official document has definitions and introductions, it is calledBlack Identifier, translated as null identifier in Chinese. An empty identifier is not an ordinary variable, but a special treatment provided by the language. It can avoid naming a certain variable and also discard a certain value when assigning.

The empty identifier is generally used in four occasions, which corresponds to the 4 pieces of code in the above example.

1. Introduce a certain package to execute only the init function in the package, but this package does not directly refer to any variables or functions of the package. Use import_ to avoid compilation errors;

2. The function has multiple return values, and ignores some of them. Similar to the use of c++11 std::ignore in std::tie;

3. Compilation period check, such as whether a certain type has implemented a certain interface;

4. If you want to execute a certain piece of code before main, of course, use init.

Example blank_identifier.go

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

Output result:

The int: 5, the float: 7.500000

Summarize

The above is the entire content of this article. I hope that the content of this article has certain reference value for your study or work. Thank you for your support. If you want to know more about it, please see the following links