The example in this article describes the switch usage in the Go language. Share to everyone for your reference. The specific analysis is as follows:
Here you may have guessed the possible form of the switch.
The case experience terminates automatically unless the Fallthrough statement is used as the ending.
Copy Code code as follows:
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 condition of the switch is executed from top to bottom and stops when the match succeeds.
e.g.
Switch I {
Case 0:
Case F ():
}
F is not invoked when i==0. )
Copy Code code as follows:
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 the two days.")
Default
Fmt. Println ("Too far Away.")
}
}
A switch with no conditions is the same as switch true.
This structure makes it possible to write long if-then-else chains in a clearer form.
Copy Code code as follows:
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 will help you with your go language program.