Go Basics

Go Switch

Description

A generic switch. Cases are evaluated top to bottom, stopping when a match is found. No `break` is needed (automatic break). Use `fallthrough` to force continuation.

Pros & Cons

✅ Pros

  • Cleaner than many if-else chains.
  • Flexible: Can switch on types or values.

❌ Cons

  • Fallthrough behavior is opposite to C/Java (opt-in instead of opt-out).

When to Use

Multi-way branching.

Example

Switch on value and type.

// Basic Switch
os := "darwin"
switch os {
case "darwin":
    fmt.Println("OS X")
case "linux":
    fmt.Println("Linux")
default:
    fmt.Println("Windows?")
}

// Tagless Switch (like if-else)
t := 10
switch {
case t < 12:
    fmt.Println("Morning")
case t < 17:
    fmt.Println("Afternoon")
}

Best Practices

Use switch for clearer readability when checking multiple conditions.

← Go ConditionsGo Loops →