Module initialization in Go - Time & Space Complexity
When a Go program starts, it runs special setup code called module initialization.
We want to see how the time to run this setup changes as the program grows.
Analyze the time complexity of the following code snippet.
package main
import "fmt"
var data = initialize()
func initialize() []int {
result := make([]int, 0, 1000)
for i := 0; i < 1000; i++ {
result = append(result, i)
}
return result
}
func main() {
fmt.Println(len(data))
}
This code runs a function to fill a list with 1000 numbers before main starts.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The for-loop that runs 1000 times to add numbers to the list.
- How many times: Exactly 1000 times, once for each number added.
Imagine if the loop count changed from 10 to 100 to 1000.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 loop steps |
| 100 | 100 loop steps |
| 1000 | 1000 loop steps |
As the number of items to initialize grows, the work grows in a straight line.
Time Complexity: O(n)
This means the setup time grows directly with how many items we prepare before the program runs.
[X] Wrong: "Module initialization always takes constant time no matter what."
[OK] Correct: If the initialization code loops over many items, the time grows with that number, not fixed.
Understanding how setup code scales helps you write programs that start quickly and handle bigger data smoothly.
"What if the initialization function called another function that also loops over the data? How would the time complexity change?"
Practice
init function in a Go module?Solution
Step 1: Understand the role of
Theinitin Goinitfunction is designed to run automatically before themainfunction starts.Step 2: Differentiate from other functions
Unlikemain,initis used for setup tasks, not for program entry or input handling.Final Answer:
To run setup code automatically beforemainstarts -> Option AQuick Check:
initruns beforemain[OK]
init runs before main automatically [OK]- Confusing
initwithmain - Thinking
inithandles user input - Assuming
initmust be called manually
init function in Go?Solution
Step 1: Recall Go function syntax
In Go, functions start with the keywordfunc, followed by the function name and parentheses.Step 2: Check
Theinitfunction naming rulesinitfunction must be lowercase and have no parameters or return values.Final Answer:
func init() {} -> Option BQuick Check:
Correctinitsyntax = func init() {} [OK]
init with empty parentheses [OK]- Capitalizing
Initinstead ofinit - Using wrong keywords like
function - Adding parameters or return types to
init
package main
import "fmt"
func init() {
fmt.Println("Init 1")
}
func init() {
fmt.Println("Init 2")
}
func main() {
fmt.Println("Main")
}Solution
Step 1: Understand multiple
Allinitfunctions execution orderinitfunctions run automatically beforemain, in the order they appear in the source file.Step 2: Trace the output sequence
First, "Init 1" prints, then "Init 2", and finally "Main" from themainfunction.Final Answer:
Init 1 Init 2 Main -> Option CQuick Check:
Multipleinitrun in order beforemain[OK]
init run top to bottom before main [OK]- Assuming
mainruns beforeinit - Thinking
initfunctions run in random order - Confusing output order of
initfunctions
init function:package main
func init() {
fmt.Println("Starting")
}
func main() {
fmt.Println("Running")
}Solution
Step 1: Check for required imports
The code usesfmt.Printlnbut does not import thefmtpackage, causing a compile error.Step 2: Validate other code parts
initcan print output, multipleinitare optional, andmainmust be lowercase.Final Answer:
Missing import of the fmt package -> Option DQuick Check:
Useimport "fmt"to fix [OK]
- Forgetting to import
fmt - Thinking
initcannot print - Misnaming
mainfunction
init to do this?var config map[string]string
func init() {
// What should go here?
}Solution
Step 1: Understand map initialization in
The globalinitconfigvariable must be assigned a new map usingmakebefore adding keys.Step 2: Check each option
config = make(map[string]string) config["env"] = "production" correctly initializes and sets a key. config := map[string]string{"env": "production"} uses := which creates a new local variable, not affecting the global. var config = map[string]string{"env": "production"} declares a localconfiginsideinit, not affecting the global. config = nil setsconfigto nil, which is not useful.Final Answer:
config = make(map[string]string) config["env"] = "production" -> Option AQuick Check:
Usemaketo initialize maps before use [OK]
make to initialize maps before adding keys [OK]- Using := inside
initcreates local variable - Not initializing map before assignment
- Setting map to nil instead of a new map
Ready to prove it?
Pass the test and this pattern moves unknown
