Example analysis of switch usage in Go language

  • 2020-05-26 09:17:54
  • OfStack

This article illustrates the use of switch in the Go language. Share with you for your reference. The specific analysis is as follows:

Here you might have guessed the possible form of switch.
case will terminate automatically, unless it ends with an fallthrough statement.

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.", os)
 }
}

The execution of the switch condition from top to bottom stops when the match is successful.

(e.g.,

switch i {
case 0:
case f():
}
f is not called when i==0.)

package main
import (
 "fmt"
 "time"
)
func main() {
 fmt.Println("When's Saturday?")
 today := time.Now().Weekday()
 switch time.Saturday {
 case today+0:
  fmt.Println("Today.")
 case today+1:
  fmt.Println("Tomorrow.")
 case today+2:
  fmt.Println("In two days.")
 default:
  fmt.Println("Too far away.")
 }
}

switch without conditions is the same as switch true 1.

This 1 construct makes it possible to write long if-then-else chains in a clearer form.

package main
import (
 "fmt"
 "time"
)
func main() {
 t := time.Now()
 switch {
 case t.Hour() < 12:
     fmt.Println("Good morning!")
 case t.Hour() < 17:
     fmt.Println("Good afternoon.")
 default:
     fmt.Println("Good evening.")
 }
}

I hope this article has been helpful to the programming of Go language.


Related articles: