The init() Function
As we have discussed, every Go program (executable) starts in the main
package and the entry point is the main
function. There is another special function that we should be aware of, called init()
. Each source file can have an init()
function, but for now, we will look at the init
function in the context of the main
package. When you start writing packages, you might need to provide some initialization (the init()
function) for the package. The init()
function is used to set up states or values. The init()
function adds initialization logic for your package. Here are some examples of uses of the init()
function:
- Setting database objects and connections
- The initialization of package variables
- Creating files
- Loading configuration data
- Verifying or repairing the program state
The init()
function requires the following pattern to be called:
- Imported packages are initialized first.
- Package-level variables are initialized. ...