If, Else & Switch
Go's control flow is explicit and readable.
Introduction
Go's control flow is explicit and readable. if statements support initialization statements (if err := fn(); err != nil), eliminating temp variables. switch auto-breaks (no fallthrough unless specified) and supports expression-less switches for clean multi-branch logic.
Go 1.22 enhanced switch to accept any comparable type and improved for-loop variable scoping. Pattern-style switches on type are done via type switches — a distinct construct covered with interfaces later.
Mastering guard clauses (early return on error), switch on enums, and avoiding deep nesting is essential for readable handlers, middleware, and service methods interviewers will review in take-home assignments.
The story
An API gateway health checker classifies upstream responses before routing traffic: 2xx is healthy, 429 triggers backoff, 5xx marks the origin degraded. SRE dashboards at companies like Stripe use similar branching logic — guard clauses reject malformed status codes before severity rules run.
switch on HTTP status ranges keeps the routing table readable compared to deeply nested if chains that become unmaintainable across dozens of microservices.
Understanding the topic
Key concepts
- if init; condition { } — init statement scoped to if/else block.
- else if chains handle multiple conditions; else is optional.
- switch expression { case val: } — no break needed; fallthrough is explicit.
- switch without expression equals switch true — cleaner than if-else chains.
- case supports comma-separated values: case 1, 2, 3:
- Type switch: switch v := x.(type) { case int: } for interface values.
Step-by-step explanation
- Evaluate if condition; execute first matching block.
- Init statement in if runs once; variables scoped to if/else.
- switch evaluates cases top-to-bottom; first match executes.
- default case runs when no case matches.
- fallthrough continues to next case — rarely used, document why.
- Type switch binds variable to concrete type in each case.
Practical code example
HTTP-style routing logic with if-init error pattern and switch on status:
package mainimport "fmt"type Status stringconst (StatusActive Status = "active"StatusPending Status = "pending"StatusDisabled Status = "disabled")func describeAccount(status Status, balance float64) string {switch status {case StatusActive:if balance <= 0 {return "active but zero balance"}return fmt.Sprintf("active with balance %.2f", balance)case StatusPending:return "awaiting verification"case StatusDisabled:return "account disabled"default:return "unknown status"}}func main() {fmt.Println(describeAccount(StatusActive, 150.75))fmt.Println(describeAccount(StatusPending, 0))}
Output
active with balance 150.75 awaiting verification
Line-by-line code explanation
type Status stringcreates a new type based on string, so status values have their own type.StatusActive Status = "active"declares a typed constant. The two lines after it, for pending and disabled, define the other allowed statuses the same way.func describeAccount(status Status, balance float64) string {takes a status and a balance and returns a description as a string.switch status {compares status against each case in order and runs only the first matching one; Go does not fall through to the next case.if balance <= 0 {inside the active case, an if checks for a zero or negative balance and returns early with "active but zero balance".return fmt.Sprintf("active with balance %.2f", balance)builds and returns a string with the balance shown with two decimals. It runs only when the balance is above zero.case StatusPending:matches the pending status and returns the text "awaiting verification". The disabled case below it works the same way.default:runs when no case matched, returning "unknown status".fmt.Println(describeAccount(StatusActive, 150.75))calls the function with an active status and a positive balance, then prints the result. The next line does the same for pending with a balance of 0.
Key takeaway: A switch on a typed constant reads more clearly than a long chain of if and else if. The default case catches values you did not list, and each case returns on its own, so no break is needed.
Real-world use
Where you'll use this in production
- HTTP middleware branching on method, path, and headers.
- Validation pipelines with early return on first failure.
- State machine transitions in order processing services.
- Error classification switching on error types or codes.
Best practices
- Use guard clauses — return early instead of deep nesting.
- Prefer switch over long if-else chains for discrete values.
- Always include default case in switch for exhaustiveness awareness.
- Use if err := ...; err != nil immediately after calls returning error.
- Avoid fallthrough unless documenting C-style intentional fall-through.
- Extract complex conditions into well-named boolean variables.
Common mistakes
- Using switch with fallthrough accidentally — Go breaks by default unlike C.
- Comparing floats with == in conditions — use epsilon or integer cents.
- Deep nesting beyond 3 levels — refactor to functions or early return.
- Forgetting braces on if — Go requires them always.
- Type switch without ok check on type assertion elsewhere.
Advanced interview questions
Interview Prep
Practice concise answers, then expand each card for the explanation.
1BeginnerQuestionif init statement purpose?+
Answer
2BeginnerQuestionDoes Go switch fall through?+
Answer
3IntermediateQuestionSwitch without expression?+
Answer
4IntermediateQuestionRefactor nested ifs in legacy handler?+
Answer
5AdvancedQuestionModel complex insurance rules maintainably in Go.+
Answer
Summary
if init; cond scopes temporary variables cleanly for error checks. switch auto-breaks; use for enums and multi-value cases. Guard clauses and early return beat deep nesting. Type switches handle interface{} or any values safely. Next lesson: for loops — Go's only looping construct.