Expression Switch
Syntax:
switch optstatement; optexpression{
case expression1: Statement..
case expression2: Statement..
...
default: Statement..
}
Example:
package main
import "fmt"
func main() {
switch color:=3; color{
case 1:
fmt.Println("Red")
case 2:
fmt.Println("Blue")
case 3:
fmt.Println("Black")
case 4:
fmt.Println("Pink")
case 5:
fmt.Println("Orange")
default:
fmt.Println("Invalid")
}
}
=> Output
Black
Type Switch
Syntax:
switch optstatement; typeswitchexpression{
case typelist 1: Statement..
case typelist 2: Statement..
...
default: Statement..
}
Example:
package main
import "fmt"
func main() {
var value interface{}
switch q:= value.(type) {
case bool:
fmt.Println("value is of boolean type")
case float64:
fmt.Println("value is of float64 type")
case int:
fmt.Println("value is of int type")
default:
fmt.Printf("value is of type: %T", q)
}
}
Output:
value is of type: <nil>