Init function
An init function is a special Go package-level function that runs automatically during package initialization before ordinary program execution.
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.
Related concepts
- packagepart of · A package is a programming-language namespace and organizational unit that groups related code and may define import, compilation, or access boundaries.
- exceptioncontrasts with · An exception is a runtime signal or object representing an abnormal condition that interrupts ordinary program flow and may be handled or propagated.
- connection poolinguses · Connection pooling is a resource-management technique that maintains a collection of established connections for reuse across multiple operations.
- command-line argumentconfigures · A command-line argument is a value supplied to a program when it is invoked, either as positional input or as an option that configures its behavior.
- testcontrasts with · A test is a procedure or check that evaluates behavior using specified inputs or evidence against expected results or criteria.
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.

