init Function

Part of Golang Mastery course

~15 min read
Interactive
Hands-on
Beginner-friendly

init Function

Identifier main is ubiquitous. Every Go program starts in a package main by calling identically named function. When this function returns the program end its execution. Functions init also play special role which are defined in package block and are usually used for:

  • variables initialization if cannot be done in initialization expression.
  • registering.
  • running one-time computations.

init() function will be executed first before main function

example.go
package main
 
import string">"fmt"
 
func main() {
fmt.Println(string">"main() will run second")
}
 
func init() {
fmt.Println(string">"init() will run first")
}
 
 

playground

If we run the code it will give us result

Output init() will run first main() will run second

init() function to use for variables initialization.

given two examples, the first example is code without init() function.

example.go
 
package main
 
import string">"fmt"
 
var weekday string
 
func main() {
fmt.Printf(string">"Today is %s", weekday)
}
 

playground

In this example, we declared a global variable called weekday. By default, the value of weekday is an empty string.

Because the value of weekday is blank, when we run the program, we will get the following output:

Output Today is

We can fill in the blank variable by introducing an init() function that initializes the value of weekday to the current day.

the second example is code with init() function.

example.go
package main
 
import (
string">"fmt"
string">"time"
)
 
var weekday string
 
func init() {
weekday = time.Now().Weekday().String()
}
 
func main() {
fmt.Printf(string">"Today is %s", weekday)
}
 

playground

Now when we run the program, it will print out the current weekday:

Output Today is Tuesday

init() as properties

init function doesn't take arguments neither returns any value. In contrast to main, identifier init is not declared so cannot be referenced.

example.go
package main
 
import (
string">"fmt"
)
 
var weekday string
 
func init() {
fmt.Println(string">"hello init")
}
 
func main() {
init()
}
 

playground

When we run it will give the result of error

/prog.go:14:5: undefined: init

Many init function can be defined in the same package or file

example.go
package main
 
import string">"fmt"
 
func init() {
fmt.Println(string">"init in 1")
}
 
 
func init() {
fmt.Println(string">"init in 2")
}
 
func main() {
fmt.Println(string">"main")
}
 

playground

When we run the code it will give the result

Output init in 1 init in 2 main

Your Progress

41 of 103 modules
40%
Started40% Complete
Previous
SpaceComplete
Next