Go

What are the uses of the blank identifier (_)? Explain import _, var _ = , _ = x and blank struct fields.

Question 560MediumGo 1.22 to 1.25

_ is a write-only placeholder. Anything assigned to it is discarded, and it never creates a binding.

import (
	_ "embed"                      // needed for //go:embed on string/[]byte vars
	_ "github.com/jackc/pgx/v5/stdlib" // side effect: init() registers the "pgx" driver
	_ "net/http/pprof"             // registers /debug/pprof handlers on DefaultServeMux
)

// Compile-time interface satisfaction check (zero runtime cost)
var _ io.ReadWriter = (*Buffer)(nil)
var _ http.Handler = HandlerFunc(nil)

func f() {
	v, _ := m["k"]       // ignore the second result
	for _, x := range xs { _ = x }
	_ = unusedDuringDev  // silence "declared and not used" temporarily
}

type Options struct {
	_       struct{}   // forces keyed literals: Options{Timeout: 1} ok, Options{1} is an error
	Timeout int
}

type noCompare struct {
	_ [0]func()        // makes the type non-comparable, zero size
	id int
}

Details: import _ runs the package's init functions without exposing any names. Overusing it hides dependencies and global registration. var _ I = (*T)(nil) is the idiomatic assertion that "T implements I", so a broken method signature fails in the package that defines T rather than at a distant call site. Blank struct fields can't be read or set, and they keep their place in memory layout (explicit padding, cgo layouts). Putting _ [0]func() last in a struct can add padding, so put it first. Also: _ = x is sometimes written to show that a value is deliberately unused, and func (T) M(_ int) shows a parameter is unused.

More on Go Idioms, Design Patterns & Language Design

All 16 Go Idioms, Design Patterns & Language Design questions