Home »
Golang
Go main() and init() function
Last Updated : July 21, 2025
In Go, every executable program must have a main()
function defined in the main
package. This is the entry point of the program. Additionally, Go provides an init()
function which is automatically executed before the main()
function. The init()
function is commonly used to perform setup tasks like initializing variables or configurations.
The main() Function
The main()
function is where the execution of a Go program begins. It must be defined in the main
package.
Example
This example defines a basic main()
function:
package main
import "fmt"
func main() {
fmt.Println("Hello from main!")
}
When you run the above code, the output will be:
Hello from main!
The init() Function
The init()
function runs automatically before the main()
function. It’s useful for initialization logic and can be declared multiple times across different files within the same package.
Example
This example shows how init()
executes before main()
:
package main
import "fmt"
func init() {
fmt.Println("Initialization in progress...")
}
func main() {
fmt.Println("Program starts now.")
}
When you run the above code, the output will be:
Initialization in progress...
Program starts now.
Multiple init() Functions
You can define multiple init()
functions in different files of the same package. They will run in the order the files are compiled, not the order they are written.
Example
Here’s an example with two init()
functions in one file:
package main
import "fmt"
func init() {
fmt.Println("First init function")
}
func init() {
fmt.Println("Second init function")
}
func main() {
fmt.Println("Main function")
}
When you run the above code, the output will be:
First init function
Second init function
Main function
Difference Between main() and init() Functions
The main()
and init()
functions serve different purposes in a Go program, and understanding their differences is key to managing program execution flow effectively:
Point |
Description |
main() Function |
The main() function is mandatory in every executable Go program, as it serves as the program's entry point. |
init() Invocation |
The init() function runs automatically before the main() function and is invoked by the Go runtime. |
Multiple init() Functions |
There can be multiple init() functions spread across different files in the same package, and all of them will be executed. |
init() Signature |
The init() function does not take any arguments and does not return any value. |
Go main() and init() function Exercise
Select the correct option to complete each statement about main() and init() function in Go.
- What is the role of the
main()
function in Go?
- When is the
init()
function executed?
- Which of the following is true about
init()
?
Advertisement
Advertisement