How to Write Switch Statements in Go

Use Go switch statements to execute different code blocks based on a variable's value or boolean conditions.

Use the switch statement with a variable or expression to branch logic based on its value.

switch status {
case "active":
    fmt.Println("User is active")
case "inactive":
    fmt.Println("User is inactive")
default:
    fmt.Println("Unknown status")
}

For multiple conditions, use case with commas or a switch without an expression to check boolean conditions.

switch {
case status == "active":
    fmt.Println("Active")
case status == "pending":
    fmt.Println("Pending")
default:
    fmt.Println("Other")
}