Switch

Switch statements express conditionals across many branches.

import ( "time" )

Here’s a basic switch.

i := 2 print "Write ", i, " as " switch i { case 1: println "one" case 2: println "two" case 3: println "three" }

You can use commas to separate multiple expressions in the same case statement. We use the optional default case in this example as well.

switch time.now().weekday() { case time.Saturday, time.Sunday: println "It's the weekend" default: println "It's a weekday" }

switch without an expression is an alternate way to express if/else logic. Here we also show how the case expressions can be non-constants.

t := time.now() switch { case t.hour() < 12: println "It's before noon" default: println "It's after noon" }

switch with fallthrough:

score := 80 switch { case score < 50: printf "%d < 50\n", score fallthrough case score < 100: printf "%d < 100\n", score fallthrough case score < 200: printf "%d < 200\n", score }

The switch in Go+ defaults to a break at the end of each case. Use fallthrough to enforce the code for the subsequent cases.

Next example: For