liveBook · Manning

Init function

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

How 2 Manning books explain it

100 Go Mistakes and How to Avoid Them

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

How it is used
Uses automatic package initialization for state setup and deliberate side effects, while cautioning against hiding application startup inside init.
How deep it goes
Explains signatures, package dependencies, file ordering, blank imports, and testing and error-handling trade-offs, but not runtime internals.
Examples
Demonstrates variable-init output, dependent redis and main packages, multiple init functions, blank imports, database setup, and HTTP handler registration.
What you can do after
Diagnose initialization-order and startup-design problems, then move failure-prone setup into caller-controlled functions.

Read how 100 Go Mistakes and How to Avoid Them explains init function →

Go by Example

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

How it is used
Registers database drivers automatically through blank imports during package initialization.
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.

Read how Go by Example explains init function →

Related concepts

These guides are generated from the text of Manning books by Manning's knowledge graph and link to the sections they draw on. The full books are available on liveBook and at manning.com.