The blank identifier in Golang

Sometimes, a programming language needs to ignore some values for multiple reasons. Go has an identifier for this. If any variable is declared but not used or any import has the same issue, the Go compiler throws an error. Golang blank identifier helps prevent that.

What is the blank identifier?

The blank identifier is the single underscore (_) operator. It is used to ignore the values returned by functions or import for side-effects.

Why is it needed?

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.

Uses of blank identifier

The blank identifier can ignore any value. The main use cases for this identifier is to ignore some of the values returned by a function or for import side-effects.

1. Ignore values

The blank identifier ignores any value returned by a function. It can be used any number of times in a Go program. The code below shows how to use the blank identifier.

package main

import (
	"fmt"
)

func f() (int, int) {
	return 42, 53
}

func main() {
	v, _ := f()    // no error from compiler
	fmt.Println(v) // 42
}

2. Side effects of import

Sometimes, a package in Go needs to be imported solely for side effects i.e. initialization. The blank identifier if used before does that. It allows us to import the package without using anything from it. It also stops the compiler from throwing error messages like “unused import“.

import _ "fmt"

3. Ignore Compiler Errors

The blank identifier can be used as a placeholder where the variables are going to be ignored for some purpose. Later those variables can be added by replacing the operator. In many cases, it helps to debug code.

package main

import (
	"fmt"
)

func f() int {
	return 42
}

func main() {

	r := f()
	_ = r + 10     // ignore it now
	               // can add the variable later
	
	fmt.Println(r) // 42
}