Go Switch

Go Switch #

The switch statement in Go is used to simplify multiple conditional checks. Instead of using many if-else if-else statements, you can use switch to execute one block of code from multiple options.

Syntax #

switch expression {
case value1:
    // code to execute if expression == value1
case value2:
    // code to execute if expression == value2
default:
    // code to execute if expression doesn't match any case
}

How it works #

  • expression is evaluated once.
  • The value of expression is compared with each case value.
  • When a matching case is found, its block executes.
  • default is optional and executes if no case matches.

Example

package main
import ("fmt")

func main() {
    day := 3
    switch day {
    case 1:
        fmt.Println("Monday")
    case 2:
        fmt.Println("Tuesday")
    case 3:
        fmt.Println("Wednesday")
    default:
        fmt.Println("Another day")
    }
}

Result:

Wednesday

Notes #

  • Only one case block is executed by default (no fallthrough).
  • Use fallthrough keyword if you want to continue to the next case.
  • Cases do not need to be constant values; you can use expressions as well.

Next, we can create the Single-case and Multi-case subpages to show examples of one case per switch vs multiple values in one case.