Control Flow, Functions, Packages, and Code Organization
Write meaningful logic with conditionals and loops, then organize Go programs into reusable functions and packages.
Inside this chapter
- if, for, and switch
- Functions
- Multiple Return Values
- Packages and Files
- Practical Example
Series navigation
Study the chapters in order for the clearest path from Golang basics to advanced concurrency, service design, and production engineering. Use the navigation at the bottom to move smoothly through the full tutorial series.
if, for, and switch
if score >= 80 {
fmt.Println("Excellent")
} else {
fmt.Println("Keep learning")
}
for i := 0; i < 3; i++ {
fmt.Println(i)
}
Go uses for for all looping patterns and offers a clean switch syntax for branch-heavy logic.
Functions
func calculateTotal(price float64, tax float64) float64 {
return price + (price * tax)
}
Functions define reusable logic and explicit input-output contracts. Go makes return types highly visible, which improves readability.
Multiple Return Values
func divide(a, b float64) (float64, error) {
if b == 0 {
return 0, errors.New("division by zero")
}
return a / b, nil
}
Go commonly returns a value and an error together. This pattern is central to Go code style and influences how error handling works throughout the language.
Packages and Files
Go code is organized into packages rather than one giant global scope. Good package structure makes larger systems easier to navigate, test, and maintain.
Practical Example
A small backend service may have separate packages for handlers, business logic, data access, and configuration. Package-level organization helps teams reason about ownership and boundaries cleanly.