0
0
Goprogramming~10 mins

Module initialization in Go - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - Module initialization
Start Program
Import Packages
Run init() functions in imported packages
Run init() in main package
Execute main() function
Program Ends
The program starts by importing packages, then runs all init() functions in order, and finally runs main().
Execution Sample
Go
package main
import "fmt"
func init() {
    fmt.Println("Init called")
}
func main() {
    fmt.Println("Main called")
}
This Go program prints messages from init() first, then from main().
Execution Table
StepActionOutputNext Step
1Start programImport packages
2Import packagesRun init() functions in imported packages
3Run init() in main packageInit calledExecute main() function
4Execute main() functionMain calledProgram ends
5Program endsNo further steps
💡 Program ends after main() completes
Variable Tracker
VariableStartAfter init()After main()Final
No variables----
Key Moments - 2 Insights
Why does init() run before main() even though main() is the entry point?
init() functions run automatically after package imports and before main(), as shown in execution_table step 3 before step 4.
Can there be multiple init() functions?
Yes, each package can have multiple init() functions, all run before main(), as indicated in step 2 and 3 of execution_table.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is printed at step 3?
AProgram starts
BMain called
CInit called
DNo output
💡 Hint
Check the Output column at step 3 in execution_table
At which step does the main() function run?
AStep 2
BStep 4
CStep 3
DStep 5
💡 Hint
Look at the Action column to find when main() executes
If there were multiple imported packages each with init(), when would they run?
ABefore main(), during package import
BOnly if called explicitly
CAfter main()
DThey do not run automatically
💡 Hint
Refer to execution_table step 2 and 3 about init() timing
Concept Snapshot
Go module initialization:
- Program starts by importing packages
- All init() functions run automatically after imports
- init() runs before main()
- main() is the program entry point
- Multiple init() functions can exist and run in order
Full Transcript
In Go, when a program starts, it first imports all required packages. After importing, Go runs all init() functions found in those packages automatically. Then, it runs the init() function in the main package. Only after all init() functions finish does the main() function run. This means init() functions prepare the program before main() starts. Multiple init() functions can exist and they all run before main(). The program ends after main() completes.