A switch
statement is a shorter way to write a sequence of if-else
statements. switch
runs the first case whose value is equal to the condition expression.
switch
is passed a variable whose value is compared to each case value. If there is a match, the corresponding block of code is executed.
switch optstatement; optexpression{
case expression1: Statement..
case expression2: Statement..
...
default: Statement..
}
optstatement
and optexpression
in the expression switch are optional statements.optstatement
and optexpression
are present, then a semi-colon(;) is required in-between them.case
expressions compares the switch variable’s value with the expression value. If the values match, the statements inside that particular switch are executed.The following code demonstrates a simple switch-case
example:
Go’s switch is like the one in C, C++, Java, JavaScript, and PHP, except that Go only runs the selected case, not all the cases that follow.
package mainimport ("fmt")func main() {i := 2fmt.Print("Write ", i, " as ")switch i {case 1:fmt.Println("one")case 2:fmt.Println("two")case 3:fmt.Println("three")}}
The code below shows how switch
without an expression is an alternate way to express if/else
logic. The code also shows how the case expressions can be non-constant.
package mainimport ("fmt""time")func main() {t := time.Now()fmt.Println(t)switch {case t.Hour() < 12:fmt.Println("It's before noon")default:fmt.Println("It's after noon")}}
package mainimport "fmt"func main() {switch i:=2; i{case 1:fmt.Println("one")case 2:fmt.Println("two")case 3:fmt.Println("three")}}
Free Resources