HomeToolsAbout a20k

Switch

What is it

A switch statement is a shorter way to write a sequence of if - else statements.

It runs the first case whose value is equal to the condition expression.

package main import ( "fmt" "runtime" ) func main() { os := runtime.GOOS switch os { case "darwin": fmt.Println("OS X.") case "linux": fmt.Println("Linux.") case "windows": fmt.Println("Window.") default: fmt.Printf("%s.\n", os) // freebsd, openbsd, plan9 } }

Skip Expression and Eval Every Time

Statement to run switch on every evaluation

other_var_for_conditional := "some_value" switch true { case other_var_for_conditional == "not this": fmt.Println("no") case other_var_for_conditional == "not this either": fmt.Println("no") case other_var_for_conditional == "some_value": fmt.Println("yes") default: fmt.Printf("no")
© VincentVanKoh