Intermediate 15 min readModule: Module 3: Control Flow (if, switch, for)
If Initializers, Switch & The Unified 'for' Loop
Master if statements with inline initializers (if err := ...; err != nil) and unified for loops.
What You Will Learn in This Lesson
- If statements with local variable initialization scope
- Why Go has only one loop keyword ('for') that handles while, infinite, and range loops
- Switch statements without explicit break requirements
Introduction & Core Concept
Go intentionally simplifies control flow: 'for' is the only loop construct, and 'switch' breaks automatically without fallthrough.
WHY DOES THIS MATTER IN THE REAL WORLD?
The 'if err := doWork(); err != nil' pattern scopes the error variable strictly to the conditional block.
If with Initializer & For-Range Loop
gogo
123456789package mainimport "fmt"func main() {scores := []int{95, 88, 92}for idx, score := range scores {fmt.Printf("Student #%d Score: %d\n", idx+1, score)}}
Line-by-Line Technical Breakdown
1Go switch statements support multiple case matches (case 1, 2, 3:).
Try It Yourself (Interactive Editor)
Modify the code in real-time and click Run to test live browser output and console logs.
Intelligent Code Runner & Live Sandbox[GO]
GO SOURCE EDITOR
Interactive Live CodeIndustry Best Practices & Professional Standards
- Use if initializers to scope temporary variables cleanly.
Lesson Summary & Core Takeaways
- Go's unified control flow constructs keep codebases simple and readable.