package main
import "fmt"
func f() int {
fmt.Println("f!")
return 1
}
func getFavoriteThing() string {
return "cookies"
}
func main() {
////////////////////////////////
// A basic switch
////////////////////////////////
animal := "pony"
switch animal {
case "frog":
fmt.Println("Ribbit")
case "pony":
fmt.Println("Neigh")
fallthrough // We use fallthrough to fall through to the next case
case "dog":
fmt.Println("Bark")
default:
fmt.Println("Noise")
}
///////////////////////////////
// Using a simple statement
///////////////////////////////
switch fave := getFavoriteThing(); fave {
case "cookies":
// We have access to fave in the switch
fmt.Println(fave)
default:
fmt.Printf("WRONG! Should have been %s", fave)
}
// We no longer have access to fave out here.
///////////////////////////////
// You can make function calls in your cases...
// As long as the types agree
///////////////////////////////
i := 1
switch i {
case 0:
fmt.Println("Case 0")
case f():
fmt.Println("Case f()")
}
/////////////////////////////
// By default, a switch will switch on true.
// This is an idiomatic alternative to a big if-else chain.
/////////////////////////////
x, y := 42, 42
switch {
case x > y:
fmt.Println("Case x > y")
case x < y:
fmt.Println("Case x < y")
default:
fmt.Println("Case x == y")
}
}