DAY 3 — Structs and Modeling Data (One Concept at a Time)
Goal (End of Day 3)
- Understand what a struct is
- Create and use structs
- Pass structs to functions
- Understand value vs pointer usage at a basic level
- Model simple real-world data in Go
- What a Struct Is
Concept
- A struct groups related values under one name
Example
type Person struct {
Name string
Age int
}
Rules
- Fields have names and types
- Field order matters for readability, not access
- Structs define shape, not behavior
Exercise
- Define a struct representing a Book (title, author, pages)
- Creating and Using Struct Values
Concepts
- Struct literals
- Accessing fields with dot notation
Example
p := Person{Name: "Alice", Age: 30}
fmt.Println(p.Name)
Rules
- Field names must match the struct definition
- Unspecified fields get zero values
Exercise
- Create a Book value and print its fields
- Passing Structs to Functions
Concepts
- Structs can be passed like any other value
- Functions can return structs
Example
func printPerson(p Person) {
fmt.Println(p.Name, p.Age)
}
Exercise
- Write a function that takes a Book and returns a formatted string
- Pointers to Structs (Intro Only)
Concepts
- Using *T to avoid copying large structs
- Modifying struct fields via pointers
Example
func birthday(p *Person) {
p.Age += 1
}
Rules
- Use pointers when a function needs to modify the struct
- Go handles pointer dereferencing automatically for structs
Exercise
- Write a function that increments the page count of a Book
- Mini Program (Mandatory)
Program: Library Item
Requirements
- Define a struct for an item (ID, Name, Count)
- Create a slice of items
- Write a function that updates Count by ID
- Handle missing ID with an error
Exit Criteria (Must All Be True)
- Defined at least one struct
- Created struct values correctly
- Passed structs to functions
- Used a pointer to modify a struct
- Program compiles and runs cleanly
Day 4 Preview
- Methods on structs
- Value vs pointer receivers
- Attaching behavior to data