Functions in Go
Functions are first-class in Go. Multiple return values eliminate need for output parameters; errors are typically the last return.
Basic Functions
func add(a, b int) int {
return a + b
}
func divide(a, b float64) (float64, error) {
if b == 0 {
return 0, fmt.Errorf("division by zero")
}
return a / b, nil
}
Named Returns
func split(sum int) (x, y int) {
x = sum * 4 / 9
y = sum - x
return // naked return
}
Variadic
func sum(nums ...int) int {
total := 0
for _, n := range nums {
total += n
}
return total
}
fmt.Println(sum(1, 2, 3, 4))
Methods
type Rectangle struct { W, H float64 }
func (r Rectangle) Area() float64 {
return r.W * r.H
}
func (r *Rectangle) Scale(f float64) {
r.W *= f; r.H *= f
}
Functions as Values
apply := func(f func(int) int, x int) int {
return f(x)
}
result := apply(func(x int) int { return x * 2 }, 5)
Common Pitfalls
- Ignoring returned errors in Go or fighting the borrow checker in Rust.
- Premature optimization before profiling.
- Skipping tests for concurrent and error paths.
- Not reading standard library documentation.
Best Practices
- Follow language idioms (Go: explicit errors; Rust: ownership).
- Write table-driven tests.
- Use
go fmt/cargo fmtconsistently. - Keep functions small and focused.
Memory and Performance Notes
Small functions inline well. Large functions benefit from escape analysis awareness.
Exercise
Write a function returning min, max, and average of a []int slice.
Hint: Handle empty slice edge case — return error or use math package.
Summary
Practice these concepts in small programs before building production services.
Debugging Checklist
- Read the full error message.
- Reduce to minimal reproduction.
- Check types and return values.
- Add logging at decision points.
- Write a test that catches the bug.
Real-World Application
Production services combine these fundamentals with logging, metrics, and graceful degradation.
Further Reading
Official language documentation, effective guides, and mature open-source projects.
Additional Examples
Consider how this topic applies in a larger project:
// Break the problem into smaller functions
// Test each function independently
// Integrate incrementally
Working through variations of the examples above builds deeper understanding than reading alone.
Interview and Review Questions
- Explain the core concept of this topic in your own words.
- What happens when this code runs with edge-case input (empty, null, zero, max value)?
- How would you debug a bug related to this topic in production?
- What are the performance implications of the approach shown here?
- How does this feature compare to the equivalent in another language you know?
Related Topics in This Path
Review adjacent pages in the learning path before and after this one. Concepts build on each other — skipping ahead often leads to confusion when later pages assume mastery of earlier material.
Return to the section index if you need to fill gaps in prerequisite knowledge.