
What is init function?
An init function is a function used to initialize the state of an application. It takes no arguments and returns no result( a func() function). When a package is initialized, all the constant and variable declarations in the package are evaluated. Then, the init functions are executed.
Init
Function
Example
Misuse of init function during database connection
Holding
database
connection
pool
through
init
function
The downslides of init function in this case.
- Error management in init function is limited. There is no return type in init function so we always have to panic in case of error(If database connection fails).
- The unit testing due to init function may be complicated as the init function will be executed before running the test cases. If we add unit tests on a utility function that doesn’t require the dependency written in init function. Even in this case, the dependency should be handled while running the test cases.
- Any variable in init function if needed to be accessed outside the init function then the variable should always be made global(e.g db *Sql.DB) which makes the unit test complicated and any functions can alter that variable within the package.
We can limit the downslides of init function in above case by creating user function for connection to database as below:-

Here, we have solved few issues:-
- Error is handled by caller.
- Unit tests without dependency on database should run without the need of initialization of database.
- We don’t need to use global variable.
So while creating init function we have to think about following points:-
- There’s no need to create any global variables.
- The init function should not impact possible unit tests.
- Proper error management is not required for the implementation of the function.
In this way, we can avoid misusing the init function in our code.
References:-
- 100 Go Mistakes and how to avoid them, Teiva Harsanyi, Manning Publications Co