Switch Statements

switch statements are an alternative to long if-else chains. They are often more readable when you have multiple discrete options to check.

Basic Syntax

In Go, the break statement is implicit. You don’t need to add it at the end of every case; Go will automatically exit the switch block once a match is found.

switch os {
case "linux":
    fmt.Println("Open source!")
case "windows":
    fmt.Println("Microsoft")
case "mac":
    fmt.Println("Apple")
default:
    fmt.Println("Unknown OS")
}

Fallthrough

If you explicitly want a case to “fall through” to the next one, you can use the fallthrough keyword.

switch status {
case "urgent":
    sendAlert()
    fallthrough
case "important":
    logToDatabase()
case "normal":
    // just normal processing
}

The Default Case

The default case runs if none of the other cases match. It is optional but recommended for handling unexpected values.