liveBook · Manning

Init function

As explained in Go by Example

An init function is a special Go function that runs automatically during package initialization before program execution begins.

An init function runs automatically when its package is initialized. Importing a package executes its init functions once, even when multiple packages import it. section 10.1.1

A blank import uses a package for its side effects without referring to its package name. This pattern lets a driver register itself before the application uses database/sql. section 10.1.1

Registering an SQLite driver

package sqlite import ( _ "modernc.org/sqlite" ) The imported driver defines init, which calls sql.Register("sqlite", newDriver()). The database/sql package stores the driver in its registry, making it available to later database operations.

Use init functions deliberately:

  • Reserve them for rare cases such as global registry setup. section 10.1.1
  • Prefer explicit initialization when maintainability and execution clarity matter. section 10.6

How Go by Example covers it

How deep it goes
Explains one-time implicit execution and demonstrates registry registration, while recommending explicit initialization for most other cases.
Examples
Demonstrates blank-importing modernc.org/sqlite and registering the driver in database/sql.
What you can do after
Operate SQLite driver registration by adding a blank import and understanding its automatic initialization.
How it connects
Connects init functions with package imports, blank imports, global registries, database/sql, and SQLite drivers.

Also explained in

Compare how 2 books explain init function →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Go by Example. The section links point to the parts of the book it draws on.