Nested structs in Go - Time & Space Complexity
When working with nested structs in Go, it's important to understand how accessing and processing them affects the time your program takes.
We want to see how the time grows when we work through nested structs.
Analyze the time complexity of the following code snippet.
type Address struct {
City string
State string
}
type Person struct {
Name string
Age int
Address Address
}
func printCities(people []Person) {
for _, p := range people {
fmt.Println(p.Address.City)
}
}
This code loops through a list of people and prints the city from their nested Address struct.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping through the slice of people.
- How many times: Once for each person in the list.
As the number of people increases, the number of times we print cities grows at the same rate.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 prints |
| 100 | 100 prints |
| 1000 | 1000 prints |
Pattern observation: The work grows directly with the number of people.
Time Complexity: O(n)
This means the time to run grows in a straight line with the number of people.
[X] Wrong: "Accessing nested structs makes the time complexity multiply or become slower than linear."
[OK] Correct: Accessing fields inside nested structs is a direct operation and does not add extra loops, so it does not increase the overall time complexity beyond the main loop.
Understanding how nested structs affect time helps you explain your code clearly and shows you know how data structures impact performance.
"What if we added a nested loop inside the printCities function to loop over multiple addresses per person? How would the time complexity change?"