SoFunction
Updated on 2025-03-03

Example analysis of switch usage in Go language

This article describes the usage of switch in Go language. Share it for your reference. The specific analysis is as follows:

Here you may have guessed the possible form of switch.
The case experience automatically terminates unless the fallthrough statement ends.

Copy the codeThe code is as follows:
package main
import (
 "fmt"
 "runtime"
)
func main() {
 ("Go runs on ")
 switch os := ; os {
 case "darwin":
  ("OS X.")
 case "linux":
  ("Linux.")
 default:
  // freebsd, openbsd,
  // plan9, windows...
  ("%s.", os)
 }
}

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

(For example,

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

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

A switch without conditions is the same as switch true.

This construction allows long if-then-else chains to be written in clearer form.

Copy the codeThe code is as follows:
package main
import (
 "fmt"
 "time"
)
func main() {
 t := ()
 switch {
 case () < 12:
     ("Good morning!")
 case () < 17:
     ("Good afternoon.")
 default:
     ("Good evening.")
 }
}

I hope this article will be helpful to everyone's Go language programming.