Init Function
In this tutorial, we are going to discuss about init function on Go language.

When we write Go packages, you can provide a function βinitβ that will be called at the beginning of the execution time. The init method can be used for adding initialization logic into the package.
In general Applications have initialization requirements. And init() function is Golangβs solution to the initialization problem. This function is executed before main().
package db import ( "gopkg.in/mgo.v2" "gopkg.in/mgo.v2/bson" ) func init { // initialization code here }
In some contexts, we may need to import a package only for invoking itβs init method, where we donβt need to call forth other methods of the package.
If we imported a package and are not using the package identifier in the program, Go compiler will show an error. In such a situation, we can use a blank identifier ( _ ) as the package alias name.
So the compiler ignores the error of not using the package identifier, but will still invoke the init function.
package main import ( _ "mywebapp/libs/mongodb/db" "fmt" "log" ) func main() { //implementation here }
In the above sample program, we imported a package named db. Letβs say we want to use this package only for calling the init method.
The blank identifier will enable us to avoid the error from Go compiler, and we will be able to invoke the init method defined in the package.
We can use alias names for packages to avoid package name ambiguity.
package main import ( mongo "mywebapp/libs/mongodb/db" mysql "mywebapp/libs/mysql/db" ) func main() { mongodata :=mongo.Get() //calling method of package "mywebapp/libs/mongodb/db" sqldata:=mysql.Get() //calling method of package "mywebapp/libs/mysql/db" fmt.Println(mongodata ) fmt.Println(sqldata ) }
We are importing two different packages from two different locations, but the name of both packages are the same.
So we can use an alias name for one package, and can use the alias name whenever we need to call a method of that package.
Features of init() function
1. There can be multiple init() functions in a package or even in a single file
2. The order of execution of multiple init()βs is decided by the order in which the go files are passed to go build command β It is recommended that the go files are passed to go build command in lexical order.
3. Within a single file, if multiple init() functions are defined, they will be invoked in the order they are defined.
4. If test file has an init() function, then that init() will be executed before the test is executed. In other words, first, all not-test files init() functions are executed, then all test files init() functions are executed.
5. Application programmer cannot invoke init() functions. That means they cannot test the function either.
6. Even if you initialize the package multiple times, init() function will be invoked only once.