What is blank identifier
A Blank identifier is a placeholder for unused values. It is represented by an underscore(_).
Since blank identifiers have no name, they are also called anonymous placeholders.
Golang does not permit declaring unused variables or import statements. That is, you cannot declare a variable and leave it unused.
Similarly, if you import a package then you have to use it.

Blank Identifiers come to rescue in many situations as explained ahead.
1. Unused assignment variables
If a function in Go returns multiple values, you have to define equal number of variables to hold those values. But what if you need only some of those values and not others as in below example

result, error = performTask()
if error {
   // handle error

In above example, you have nothing to do with result and you don’t use it. The compiler won’t allow this by saying

result declared but not used

In this case, you can replace result with an underscore or a blank identifier as shown below

_, error = performTask()
if error {
   // handle error

Even if you declare a variable, you can ignore it with a blank identifier later as in below code.

product, error = performTask()
if error {
   // handle error

// ignore unused variable
_ = product

2. Unused imports
In Go, if you import a package, then you have to make use of it otherwise there is a compiler error.

imported and not used “<package name>”

Blank identifier can be used to resolve this compiler error.
There are two ways to use blank identifiers to resolve unused package error as shown below.

A. Declare a global blank identifier(before main() function) that access a symbol from the unused package such as Open in below code.

import "os"

var _ = os.Open

func main() {

B. Prefix the unused import with a blank identifier as below.

import _ "os"

func main(){

Blank identifiers make the code more readable by avoiding unused variable declarations through out the code.

Liked the article ? Spread the word...