Use blank imports deliberately
Use blank imports deliberately
A blank import uses _ as the local package name. It imports the package for its initialization effects without making its exported identifiers available through a local name. Use it only when those effects are part of the documented API contract, such as a package registering a driver.
Create the files shown below in a fresh directory, then run go run . there. The separator lines are file labels, not source code. Go 1.23 is used for these local examples; modules are covered in detail next.
--- go.mod ---module example.test/lesson
go 1.23
--- main.go ---package main
import ( _ "example.test/lesson/setup" "fmt")
func main() { fmt.Println("main") }
--- setup/setup.go ---package setup
import "fmt"
func init() { fmt.Println("setup initialized") }The blank import triggers setup initialization. No setup selector exists in main.go. The output is a minimal demonstration of the side effect, not a recommendation to print from init in production.
Expected output:
setup initializedmainObserve registration through a shared package
--- go.mod ---module example.test/lesson
go 1.23
--- main.go ---package main
import ( _ "example.test/lesson/plugin" "example.test/lesson/registry" "fmt")
func main() { fmt.Println(registry.Has("demo")) }
--- registry/registry.go ---package registry
var names = map[string]bool{}
func Register(n string) { names[n] = true }func Has(n string) bool { return names[n] }
--- plugin/plugin.go ---package plugin
import "example.test/lesson/registry"
func init() { registry.Register("demo") }plugin depends on registry, so the map is initialized before registration. main queries the registration after all initialization completes. This registry is a sequential teaching example, not safe for arbitrary concurrent mutation. Prefer explicit registration if dependencies or failure need to be visible.
Expected output:
trueTry it locally
Create package announce with init printing "ready". Blank-import it from main and print "start" in main. Use a fresh module with the same go.mod shown above; run go run .
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Packages and visibility 05: Use blank imports deliberately
Check the lesson objective before moving on.
Why use import _ "example.test/lesson/setup"?
Can main use setup.Run() through only a blank import?