Blank Identifier( underscore ) in GoLang

The Blank identifier in Go Language is a single underscore ( _ ) operator. But before going further on what it is and how to use it? Let’s first focus on why we need a blank identifier?

We know that the Go language doesn’t allow us to declare a variable unless we use it. Go language requires that every variable that gets declared be used somewhere in our program. In most programming languages, functions or methods can only have a single return value, but they can return multiple values in Go.

Let’s take the example of the ReadString(), which returns two values, one is the actual string, and the other is the error. Sometimes, we do not require the error value but only the actual string value returned by the function. So, we tried to leave the error value returned without using it anywhere, but that gave us an error, as shown below.

package main

import (
	"bufio"
	"fmt"
	"os"
)

func main() {

	bufferReader := bufio.NewReader(os.Stdin)

	fmt.Print("Enter your name: ")

	name, err := bufferReader.ReadString('\n')

	fmt.Println("Hello, ", name)
}

Output –

err declared but not used

So, the code was not compiled because every declared variable should be used in the Go language. So, what should we do in such a scenario? where we don’t use the variable value?

Here comes the blank identifier ( _ ) to the rescue. Assigning a value to the blank identifier essentially discards it. So, when we have a value usually assigned to a variable, but we won’t be using it anywhere in our program, we can use the blank identifier ( _ ).

To use the blank identifier, we have to type the underscore ( _ ) in place of the variable name, which is not used anywhere in the program.

package main

import (
	"bufio"
	"fmt"
	"os"
)

func main() {

	bufferReader := bufio.NewReader(os.Stdin)

	fmt.Print("Enter your name: ")

	name, _ := bufferReader.ReadString('\n') // used blank identifier instead of 'err' variable

	fmt.Println("Hello, ", name)
}

Output –

Enter your name: codekru
Hello,  codekru
Use of blank identifier( _ ) in an import statement

There is one more use of the blank identifier ( _ ) in the import statement. Generally, if we import a package, we would have to use it somewhere in the program. Because if we don’t do so, we will get an error as shown in the below program.

package main

import "fmt"

func main() {

	r := 12

	r = r + 12
}

Output –

imported and not used: "fmt"

Here we can use the blank identifier just after the import keyword

package main

import _ "fmt"

func main() {

	r := 12

	r = r + 12
}

Now, if you run the program, it will compile just fine.

We hope that you have liked the article. If you have any doubts or concerns, please feel free to write us in the comments or mail us at [email protected].

Liked the article? Share this on

Leave a Comment

Your email address will not be published. Required fields are marked *