Go Init Functions
The init function is a special function in Go that runs automatically before the main function or any other code in the package is executed.
1. Basic Usage
You don't call init() yourself. Go calls it for you.
2. Execution Order
- Variables: All package-level variables are initialized first.
init()functions: Then, allinit()functions are called.main()function: Finally, themain()function is called.
3. Multiple Init Functions
You can have multiple init() functions in the same file or across multiple files in the same package. They will run in the order they appear.
Why use init()?
- Variable setup: Initializing complex global variables that can't be set with a simple assignment.
- Environment check: Checking if necessary environment variables or configuration files are present.
- Registration: Registering drivers (e.g., database drivers) or plugins.
Best Practices
- Keep it simple: Don't put heavy logic or long-running tasks in
init. It can make your program hard to test and slow to start. - Avoid side-effects: Try to keep
initfunctions focused only on setting up the internal state of the package.