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?"
Practice
struct in Go?Solution
Step 1: Understand the role of structs
Structs are used to group related data fields together in one unit, like a blueprint for an object.Step 2: Compare with other options
Functions, packages, and imports serve different purposes unrelated to grouping data.Final Answer:
To group related data fields into a single unit -> Option BQuick Check:
Struct = grouped data [OK]
- Confusing structs with functions
- Thinking structs declare packages
- Mixing structs with imports
Person with fields Name (string) and Age (int)?Solution
Step 1: Recall Go struct syntax
In Go, structs are defined using the syntax: type Name struct { fields }.Step 2: Check each option
type Person struct { Name string; Age int } matches the correct syntax. Options A, B, and C miss the 'type' keyword or 'struct' keyword placement.Final Answer:
type Person struct { Name string; Age int } -> Option CQuick Check:
Correct struct syntax = type Person struct { Name string; Age int } [OK]
- Omitting 'type' keyword
- Missing 'struct' keyword
- Incorrect order of keywords
package main
import "fmt"
type Car struct {
Brand string
Year int
}
func main() {
c := Car{Brand: "Toyota", Year: 2020}
fmt.Println(c.Brand)
}Solution
Step 1: Understand struct initialization
The struct Car is initialized with Brand="Toyota" and Year=2020.Step 2: Identify printed field
The code prints c.Brand, which is "Toyota".Final Answer:
Toyota -> Option DQuick Check:
Print c.Brand = Toyota [OK]
- Printing the whole struct instead of a field
- Confusing field names
- Expecting Year instead of Brand
package main
import "fmt"
type Book struct {
Title string
Pages int
}
func main() {
b := Book{Title: "Go Guide", Pages: "300"}
fmt.Println(b)
}Solution
Step 1: Check field types in struct initialization
The Pages field is declared as int but assigned a string "300" which is a type mismatch.Step 2: Verify other possible errors
Import for fmt package is present. Struct fields can be uppercase. Printing structs directly is allowed.Final Answer:
Pages field has wrong type, should be int not string -> Option AQuick Check:
Type mismatch in struct field assignment [OK]
- Assigning string to int field
- Expecting compilation error from printing struct
- Thinking struct fields must be lowercase
type Employee struct {
Name string
Salary int
Active bool
}
Which of the following code snippets correctly creates a slice of Employee structs with only active employees having salary above 50000?Solution
Step 1: Understand filtering criteria
We want only employees who are active and have salary above 50000.Step 2: Check each code snippet logic
emps := []Employee{{"Alice", 60000, true}, {"Bob", 45000, true}, {"Carol", 70000, false}} var filtered []Employee for _, e := range emps { if e.Active && e.Salary > 50000 { filtered = append(filtered, e) } } uses 'e.Active && e.Salary > 50000' which matches criteria. emps := []Employee{{"Alice", 60000, true}, {"Bob", 45000, true}, {"Carol", 70000, false}} filtered := []Employee{} for i := range emps { if emps[i].Salary > 50000 { filtered = append(filtered, emps[i]) } } misses active check. emps := []Employee{{"Alice", 60000, true}, {"Bob", 45000, true}, {"Carol", 70000, false}} filtered := []Employee{} for _, e := range emps { if e.Active || e.Salary > 50000 { filtered = append(filtered, e) } } uses '||' which includes inactive employees. emps := []Employee{{"Alice", 60000, true}, {"Bob", 45000, true}, {"Carol", 70000, false}} filtered := []Employee{} for _, e := range emps { if e.Active && e.Salary < 50000 { filtered = append(filtered, e) } } uses salary < 50000 which is wrong.Final Answer:
The code that filters using e.Active && e.Salary > 50000 -> Option AQuick Check:
Filter with '&&' for both conditions [OK]
- Using || instead of && for filtering
- Ignoring the Active field in filter
- Using wrong salary comparison operator
Ready to prove it?
Pass the test and this pattern moves unknown
