Rez Moss

Rez Moss

Personal Musings: A Blog for the Tech-Savvy and Curious Mind

Go's Blank Identifier: When and How to Use It

Sep 2021

The blank identifier in Go, represented by an underscore (_), is a special identifier that serves as a placeholder for values you want to ignore. Understanding when and how to use it can lead to cleaner and more idiomatic Go code.

Key Uses

  1. Ignoring Return Values When a function returns multiple values, but you’re only interested in some:

    val, _ := someFunction()
  2. Import for Side Effects To import a package solely for its initialization side effects:

    import _ "database/sql/mysql"
  3. Checking Interfaces To ensure a type implements an interface at compile time:

    var _ io.Writer = (*MyType)(nil)
  4. Loop Variables In a for range loop when you only need the index or value:

    for _, value := range slice {
       // Use value
    }
  5. Unused Variables To declare variables that might be used in future development:

    var _ = unusedVariable

Example: HTTP Handler

http.HandleFunc("/", func(w http.ResponseWriter, _ *http.Request) {
    fmt.Fprintf(w, "Hello, World!")
})

Here, the blank identifier is used because we don’t need the request parameter.

The blank identifier is a powerful tool in Go for managing unused values and imports. Used judiciously, it can make your code cleaner and more expressive.