Defining structs in Go - Time & Space Complexity
When we define structs in Go, we want to know how much time it takes to create and use them as our program grows.
We ask: How does the time to handle structs change when we have more data or more fields?
Analyze the time complexity of the following code snippet.
type Person struct {
Name string
Age int
}
func createPeople(n int) []Person {
people := make([]Person, n)
for i := 0; i < n; i++ {
people[i] = Person{Name: "Name", Age: i}
}
return people
}
This code defines a struct Person and creates a slice of n Person structs, filling each with data.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The for-loop that runs n times to create each Person struct.
- How many times: Exactly n times, once for each element in the slice.
As n grows, the number of times we create and assign structs grows the same way.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 struct creations and assignments |
| 100 | 100 struct creations and assignments |
| 1000 | 1000 struct creations and assignments |
Pattern observation: The work grows directly with n; doubling n doubles the work.
Time Complexity: O(n)
This means the time to create the structs grows in a straight line with the number of structs you want to make.
[X] Wrong: "Creating structs is instant and does not depend on how many I create."
[OK] Correct: Each struct creation takes time, so more structs mean more time spent.
Understanding how struct creation scales helps you explain how your program handles data efficiently as it grows.
"What if we added a nested struct inside Person? How would the time complexity change when creating many Persons?"