switch go code example
Example 1: go switch statement
switch time {
case "morning":
fmt.Println("Time to wake up!")
case "night":
fmt.Println("Time to go to bed.")
default:
fmt.Println("Enjoy life")
}
Example 2: go switch
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:
fmt.Printf("%s.\n", os)
}
}
Example 3: go switch case
switch time.Now().Weekday() {
case time.Saturday, time.Sunday:
fmt.Println("It's the weekend")
default:
fmt.Println("It's a weekday")
}
Example 4: go switch
switch operatingSystem {
case "darwin":
fmt.Println("Mac OS Hipster")
case "linux":
fmt.Println("Linux Geek")
default:
fmt.Println("Other")
}
switch os := runtime.GOOS; os {
case "darwin": ...
}
number := 42
switch {
case number < 42:
fmt.Println("Smaller")
case number == 42:
fmt.Println("Equal")
case number > 42:
fmt.Println("Greater")
}
var char byte = '?'
switch char {
case ' ', '?', '&', '=', '#', '+', '%':
fmt.Println("Should escape")
}