Struct usage patterns in Go - Time & Space Complexity
When using structs in Go, it is important to understand how operations on them grow as data size increases.
We want to know how the time to access or modify struct data changes when we have many structs or nested structs.
Analyze the time complexity of the following code snippet.
package main
import "fmt"
type Person struct {
Name string
Age int
}
func printNames(people []Person) {
for _, p := range people {
fmt.Println(p.Name)
}
}
func main() {
people := []Person{{"Alice", 30}, {"Bob", 25}, {"Carol", 27}}
printNames(people)
}
This code defines a struct Person and prints the Name field for each person in a slice.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping through the slice of Person structs.
- How many times: Once for each element in the slice (n times).
As the number of Person structs increases, the time to print all names grows proportionally.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 print operations |
| 100 | 100 print operations |
| 1000 | 1000 print operations |
Pattern observation: The time grows directly with the number of structs; doubling the structs doubles the work.
Time Complexity: O(n)
This means the time to process all structs grows linearly with how many structs there are.
[X] Wrong: "Accessing a field inside a struct takes extra time for each field."
[OK] Correct: Accessing a field in a struct is a direct operation and does not add extra loops or repeated work; the main time cost comes from how many structs you process.
Understanding how operations on structs scale helps you write efficient code and explain your reasoning clearly in interviews.
"What if we changed the slice of structs to a nested struct with slices inside? How would the time complexity change?"