Blank identifiers in google’s golang

Golang is made to make programming more readable and concise. It does not allow defining an unused variable. In the real programming world, we define a variable and never use it. We all do this many time.

Unused variables is a pollution in your code and with time it makes your code unreadable and buggy. Unused variables are a big problem in many languages be it Python, Java, C or C++. If you don’t keep your code clean it will be a big mess in long run.

Golang solves this problem by giving the compiler error if its compiler found any unused variable/variables. But this conflict with one of the golang’s features of returning multiple values from a function. Here is a short example to explain this.

Consider the following TOY function which fire-up the rocket engine.

func fireUpRocket() (string, bool, int) {
var message = "Howdy from rocket! We are good and going at light speed(at least it seems like)"
var error = true
var timeToReachProximaCentuary = 60 // years
return message, error, timeToReachProximaCentuary
}

The function fireUpRocket() returns three values message, error, timeToReachProximaCentuary.

Let's call fireUpRocket() from our main() function

func main() {
message, ok, timeToReachProximaCentuary := fireUpRocket()
if ok {
fmt.Printf("Rocket launch successfully.\n%s \n", message)
} else {
fmt.Printf("Rocket launch failed \n")
}
}

Let's say you are interested in only two return values message and error and you decide to use them only. Here is the point where the golang compiler will not be happy and it will give you compiler error as you left one unused variable timeToReachProximaCentuary.

Blank identifier(_) is used exactly to solve this problem. Below is the above-modified code using the blank identifier.

func main() {
// '_' is the blank identifier
message, ok, _ := fireUpRocket()
if ok {
fmt.Printf("Rocket launch successfully.\n%s \n", message)
} else {
fmt.Printf("Rocket launch failed \n")
}
}

Here is the full code

package main
import "fmt"
func fireUpRocket() (string, bool, int) {
var message = "Howdy from rocket! We are good and going at light speed(at least it seems like)"
var error = true
var timeToReachProximaCentuary = 60 // years
return message, error, timeToReachProximaCentuary
}
func main() {
// '_' is the blank identifier
message, ok, _ := fireUpRocket()
if ok {
fmt.Printf("Rocket launch successfully.\n%s \n", message)
} else {
fmt.Printf("Rocket launch failed \n")
}
}
Like what you read? Give Prakash Pandey a round of applause.

From a quick cheer to a standing ovation, clap to show how much you enjoyed this story.