Golang Switch Case

Golang Switch Case

  • Switch Case is the shorter form of writing complex if/else conditions.
  • We don't need to use break keyword inside the case block, go compiler automatically adds it.

Let's see a simple program that implements the switch case

package main

import (
    "fmt"
    "runtime"
)

func main() {
    fmt.Print("Go runs on ")
    switch os := runtime.GOOS; os {
    case "darwin":
        fmt.Println("OS X.")
    case "linux":
        fmt.Println("Linux.")
    default:
        // freebsd, openbsd,
        // plan9, windows...
        fmt.Printf("%s.\n", os)
    }
}

Note: We can use multiple values in a switch case by separating them with a comma ,.

Let's a simple function that implements it

func WhiteSpace(c rune) bool {
    switch c {
    case ' ', '\t', '\n', '\f', '\r':
        return true
    }
    return false
}