midGolang
How does the `init()` function work?
Updated Apr 28, 2026
Short answer
init() is a special function executed before main(). It is used to initialize package-level variables or state.
Deep explanation
You can have multiple init() functions in a single package or even a single file. They run automatically in the order they are declared, after all global variables are initialized. A package's init() is executed exactly once, even if imported multiple times.
Real-world example
Registering drivers, like database/sql drivers, where importing the package triggers its init() to register the specific database dialect.
Common mistakes
- Putting complex business logic or I/O operations (like database connections) in `init()`. It makes testing hard and causes silent application crashes on startup if it panics.
Follow-up questions
- Can you call `init()` explicitly from your code?