Blank Identifier(underscore)
In Go, the underscore _
is often referred to as the “blank identifier.” It’s a special identifier used when you want to discard a value returned by a function or when you want to import a package solely for its side effects without using its exported identifiers.
Here are some common use cases for the blank identifier in Go:
1. Ignoring Values: You can use the blank identifier to discard the value returned by a function or assigned to a variable when you are not interested in using that value
package main
import "fmt"
func main() {
sum, _ := calculateSumAndAverage(10, 20, 30) // Ignoring average value
fmt.Println("Sum:", sum)
}
func calculateSumAndAverage(numbers ...int) (int, float64) {
// Calculate sum and average
return sum, average
}
2. Importing for Side Effects: If you only want to execute the init
functions of a package and don’t intend to use its exported identifiers, you can use the blank identifier while importing the package.
import _ "github.com/some/package"
This will ensure that the init
functions of the imported package are executed, but you won’t be able to access its exported functions, types, or variables.
3. Unused Variables: If you declare a variable that you don’t intend to use (yet), you can use the blank identifier to avoid compilation errors.
_ = "This variable is not used"
Using the blank identifier can help you maintain clean and idiomatic Go code by explicitly indicating that a value is intentionally ignored or not used.
Here’s another example that demonstrates the use of the blank identifier to ignore function return values:
package main
import "fmt"
func main() {
// Ignoring the return values of multiple functions
_, length := getFullNameAndLength("John", "Doe")
_, area := calculateRectangleArea(5, 10)
fmt.Println("Length of full name:", length)
fmt.Println("Area of rectangle:", area)
}
func getFullNameAndLength(firstName, lastName string) (string, int) {
fullName := firstName + " " + lastName
return fullName, len(fullName)
}
func calculateRectangleArea(width, height float64) (float64, float64) {
area := width * height
perimeter := 2 * (width + height)
return area, perimeter
}
In this example, the getFullNameAndLength
function returns both the full name and its length. However, in the main
function, we’re only interested in the length, so we use the blank identifier _
to ignore the full name value returned by the function.
Similarly, the calculateRectangleArea
function returns both the area and perimeter of a rectangle. In the main
function, we’re only interested in the area, so we ignore the perimeter value using the blank identifier.
Using the blank identifier helps emphasize that certain return values are intentionally ignored and not used in the current context.