golang type switch code example
Example 1: type switch golang
var x interface{} = "foo"
switch v := x.(type) {
case nil:
fmt.Println("x is nil")
case int:
fmt.Println("x is", v)
case bool, string:
fmt.Println("x is bool or string")
default:
fmt.Println("type unknown")
}
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: golang switch
package main
import (
"fmt"
"time"
)
func main() {
isDay := time.Sunday
switch isDay {
case time.Monday:
fmt.Println("day is monday")
case time.Sunday:
fmt.Println("day is sunday")
case time.Tuesday:
fmt.Println("day is tuesday")
case time.Wednesday:
fmt.Println("day is wenesday")
case time.Thursday:
fmt.Println("day is thursday")
case time.Friday:
fmt.Println("day is friday")
case time.Saturday:
fmt.Println("day is saturday")
default:
fmt.Println("day is not exist")
}
switch browser := "firefox"; browser {
case "chrome", "opera", "firefox":
fmt.Println("my browser is", browser)
default:
fmt.Println("browser is not define")
}
var point = 6
switch {
case point == 8:
fmt.Println("perfect")
case (point < 8) && (point > 3):
fmt.Println("awesome")
default:
{
fmt.Println("not bad")
fmt.Println("you need to learn more")
}
}
}