This is a creation in Article, where the information may have evolved or changed.
When the condition determines too many branches, we use the switch statement to optimize the logic.
package mainimport "FMT" import "Time" Func main () { // The base switch usage i := 2 fmt. Print ("write ", i, " as ") switch i { case 1: fmt. Println ("one") case 2: fmt. Println (" case 3: fmt"). Println ("three") } // you can use commas to separate multiple conditions in a case. You can also use the default statement, // to 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:&nbSp; fmt. Println ("It ' S a weekday") } // when switch is not followed by an expression, function and If/else are the same, here we // can also see that the expression after the case is not necessarily a constant. t := time. Now () switch { case t.hour () < 12: fmt. Println ("It ' S before noon") default: fmt. Println ("It ' S after noon") }}
The output result is
Write 2 as Twoit ' s a weekdayit ' s before noon