Go🔧Core Languagebeginner
The Blank Identifier
Go · Core Language · Run with go run
Explanation
The blank identifier `_` is a write-only placeholder that discards a value. Go requires every declared variable and import to be used; `_` satisfies that rule when a value is intentionally unwanted — an unused return value, an unwanted range index, or an import needed only for its side effects.
Real-World Scenario
A function returns `(value, error)` but a particular call site cannot fail and only needs the value: `data, _ := json.Marshal(v)`. The blank identifier also enforces interface satisfaction at compile time: `var _ io.Reader = (*MyType)(nil)`.
Quick Snippet
snippet.go
// Discard the index, keep the value
for _, v := range items {
fmt.Println(v)
}
// Discard one of multiple returns
_, err := fmt.Println("hi")
// Import for side effects only (runs the package's init)
import _ "github.com/lib/pq"
// Compile-time interface check
var _ io.Writer = (*MyWriter)(nil)Full Example
blank_identifier.go
// Compile: go run blank_identifier.go
// Output:
// values: 10 20 30
// wrote bytes, ignored count
// MyWriter satisfies io.Writer at compile time
package main
import (
"fmt"
"io"
)
type MyWriter struct{}
func (MyWriter) Write(p []byte) (int, error) { return len(p), nil }
// Compile-time interface satisfaction check — discards the value
var _ io.Writer = (*MyWriter)(nil)
func main() {
// Discard the index in a range loop
for _, v := range []int{10, 20, 30} {
fmt.Print(" ", v)
}
fmt.Println()
fmt.Println("values: 10 20 30")
// Discard one of multiple return values
_, err := fmt.Fprint(io.Discard, "data")
if err == nil {
fmt.Println("wrote bytes, ignored count")
}
fmt.Println("MyWriter satisfies io.Writer at compile time")
}
Run command
go run blank_identifier.go