Package scope rules in Go - Time & Space Complexity
When we write Go code, variables and functions can be visible in different places. Package scope means they are visible throughout the whole package.
We want to understand how this visibility affects how often code runs and how that grows with input size.
Analyze the time complexity of the following code snippet.
package main
import "fmt"
var count int // package scope variable
func increment(n int) {
for i := 0; i < n; i++ {
count++
}
}
func main() {
increment(1000)
fmt.Println(count)
}
This code uses a package-level variable count that the increment function updates in a loop.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The for-loop inside
incrementthat runsntimes. - How many times: Exactly
ntimes, wherenis the input toincrement.
As n grows, the number of times the loop runs grows the same way.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 increments of count |
| 100 | 100 increments of count |
| 1000 | 1000 increments of count |
Pattern observation: The work grows directly with the input size. Double the input, double the work.
Time Complexity: O(n)
This means the time to run grows in a straight line with the input size.
[X] Wrong: "Because count is package scoped, the loop runs multiple times automatically."
[OK] Correct: Package scope only means the variable is visible everywhere in the package. It does not cause the loop to run more times. The loop runs exactly as many times as coded.
Understanding how package scope affects code visibility helps you reason about how often code runs and where variables change. This skill is useful when explaining code behavior clearly.
What if the increment function called itself recursively instead of using a loop? How would the time complexity change?