0
0
GoHow-ToBeginner · 3 min read

How to Use Switch in Go: Syntax and Examples

In Go, use the switch statement to select one of many code blocks to execute based on a value. It compares an expression against multiple case values and runs the matching block without needing explicit break statements.
📐

Syntax

The switch statement evaluates an expression and compares it to case values. When a match is found, the corresponding block runs. The default case runs if no matches occur. Unlike some languages, Go automatically breaks after a case unless you use fallthrough.

go
switch expression {
case value1:
    // code to run if expression == value1
case value2:
    // code to run if expression == value2
default:
    // code to run if no case matches
}
💻

Example

This example shows a switch statement that prints a message based on the day of the week.

go
package main

import "fmt"

func main() {
    day := "Tuesday"

    switch day {
    case "Monday":
        fmt.Println("Start of the work week.")
    case "Tuesday", "Wednesday", "Thursday":
        fmt.Println("Midweek days.")
    case "Friday":
        fmt.Println("End of the work week.")
    case "Saturday", "Sunday":
        fmt.Println("Weekend!")
    default:
        fmt.Println("Not a valid day.")
    }
}
Output
Midweek days.
⚠️

Common Pitfalls

  • Forgetting that Go's switch automatically breaks after each case, so no explicit break is needed.
  • Using fallthrough incorrectly, which forces execution to the next case even if it doesn't match.
  • Not including a default case to handle unexpected values.
go
package main

import "fmt"

func main() {
    num := 2

    // Wrong: fallthrough without care
    switch num {
    case 1:
        fmt.Println("One")
        fallthrough
    case 2:
        fmt.Println("Two")
    case 3:
        fmt.Println("Three")
    }

    // Right: use fallthrough only when needed
    switch num {
    case 1:
        fmt.Println("One")
    case 2:
        fmt.Println("Two")
        fallthrough
    case 3:
        fmt.Println("Three")
    }
}
Output
Two Three Two Three
📊

Quick Reference

Tips for using switch in Go:

  • Use commas to match multiple values in one case.
  • switch can be used without an expression to replace if-else chains.
  • fallthrough forces execution to the next case but use it sparingly.
  • Always include a default case for safety.

Key Takeaways

Use switch to compare an expression against multiple cases without needing breaks.
Multiple values can be matched in one case by separating them with commas.
Go automatically breaks after each case unless fallthrough is used.
Include a default case to handle unexpected values.
You can use switch without an expression as a cleaner alternative to if-else chains.