The switch statement expresses the conditional judgment through a number of branches.
Package Mainimport "FMT" import "Time" Func main () { //base switch usage i: = 2 fmt. Print ("Write", I, "as") switch I {case 1: FMT. Println ("one") Case 2: FMT. Println ("both") Case 3: FMT. Println ("three") } //You can use commas to separate multiple conditions in a case. You can also use the default statement. Execute the logical block specified by default when none of the above cases are satisfied. switch time. Now (). Weekday () {case Time . Saturday, time. Sunday: FMT. Println ("It ' s The weekend") default: FMT. Println ("It's a weekday") } //When switch does not follow the expression, the function and the if/else are the same, //Here we can see that the expression after the case is not necessarily a constant. T: = time. Now () switch {case t.hour () <: FMT. Println ("It ' s before noon") default: FMT. Println ("It ' s after noon") }}
Output
$ go Run switch.go Write 2 as Twoit ' s the Weekendit ' s before noon
Next example: Go by Example:arrays.
English original
Go by Example:switch