DAY 2 — Core Go Building Blocks (Functions, Errors, Collections)
Goal (End of Day 2)
- Write non-trivial functions outside main
- Use slices and maps correctly
- Handle errors idiomatically
- Structure small programs with clear data flow
- Read and reason about basic Go code confidently
- Functions (Beyond main)
Concepts
- Function declaration syntax
- Parameters vs return values
- Multiple return values
- Named vs unnamed returns (know both, prefer unnamed)
- Early returns
- Functions as units of behavior
Key Rules
- Go uses explicit returns
- Errors are returned, not thrown
Exercises
- Implement: add(a int, b int) int
- Implement: divide(a int, b int) (int, error)
- Implement: isEven(n int) bool
- Error Handling (Go Style)
Concepts
- error is an interface
- nil means “no error”
- if err != nil {} is mandatory
- errors.New vs fmt.Errorf
- Fail fast, return early
Key Rules
- Errors are values, not control flow
- Never ignore errors unless absolutely certain
Exercises
- Update divide to return an error on division by zero
- Handle and print user-friendly error messages in main
- Slices (Primary Data Structure)
Concepts
- Slice literals vs make
- len vs cap
- append
- for range iteration
- Zero value of a slice is nil
Key Rules
- Slices are descriptors over arrays
- append may reallocate underlying array
Exercises
- Write functions to compute sum, min, and max from a slice of ints
- Maps (Key–Value Storage)
Concepts
- Map literals vs make
- Zero value of a map is nil
- Insert, read, delete
- Comma-ok idiom
Key Rules
- Missing key returns zero value
- Use comma-ok to distinguish missing vs zero
Exercises
- Build a word-frequency counter for a string
- Print word counts (sorted optional)
- Mini Program (Mandatory)
Program: CLI Stats Tool
Requirements
- Hardcode a slice of integers
- Compute count, sum, and average using functions
- Handle empty slice gracefully
Suggested Structure
package main
func main() {
// orchestration only
}
func computeStats(nums []int) (sum int, avg float64, err error) {
}
- Tooling Rules (Non-Negotiable)
- Use gofmt or editor auto-formatting
- No unused variables
- No commented-out dead code
- Keep main thin; logic goes into functions
Exit Criteria (Must All Be True)
- At least 3 functions outside main
- Used both slices and maps
- Returned and handled real errors
- Can explain why Go avoids exceptions
- Code formats cleanly with gofmt
Day 3 Preview
- Structs
- Methods
- Value vs pointer receivers
- Basic program modeling