Module lessons (4/5)
Idiomatic switch
Go's switch is more ergonomic than C/Java's: each case has its
own implicit block (no break to write), you can group
multiple values with a comma, and a switch without an expression behaves
like a more readable if/else if chain.
Switch on a value
giorno := "mar"
switch giorno {
case "lun", "mar", "mer", "gio", "ven":
fmt.Println("feriale")
case "sab", "dom":
fmt.Println("weekend")
default:
fmt.Println("sconosciuto")
}case accepts multiple values separated by commas and there is no implicit
fallthrough: as soon as a case is executed, the switch exits.
Switch without a condition
If you omit the expression, the switch evaluates true and each case is a
bool condition. It is the idiomatic alternative to long if/else if chains:
switch {
case x < 0:
fmt.Println("negativo")
case x == 0:
fmt.Println("zero")
case x < 10:
fmt.Println("piccolo")
default:
fmt.Println("grande")
}Init statement
As with if, switch also accepts an init statement:
switch n := len(s); {
case n == 0:
fmt.Println("vuoto")
case n > 100:
fmt.Println("lungo")
default:
fmt.Println("ok")
}n exists only inside the switch.
Explicit fallthrough
If you really want execution to fall into the next case, you have to write it:
switch 1 {
case 1:
fmt.Println("uno")
fallthrough
case 2:
fmt.Println("due") // anche questo viene stampato
case 3:
fmt.Println("tre") // questo no
}Type switch (preview)
It lets you discriminate based on the dynamic type of an interface value. We will cover it in depth in the Interfaces module:
var i interface{} = "ciao"
switch v := i.(type) {
case int:
fmt.Println("int:", v)
case string:
fmt.Println("string:", v)
default:
fmt.Printf("tipo %T\n", v)
}Try it
Print 'feriale' for lun/mar/mer/gio/ven, 'weekend' otherwise, using a switch on the value of g.
Show hint
Group the 5 weekdays into a single case separated by commas.
Solution available after 3 attempts
Use a switch WITHOUT a condition to print 'neg', 'zero' or 'pos' depending on x.
Show hint
No expression after `switch`, just `{`.
Solution available after 3 attempts
What does this program print?
switch 1 {
case 1:
fmt.Print("a")
case 2:
fmt.Print("b")
}Recap
caseaccepts multiple values separated by commas.- No implicit fallthrough: each case has its own implicit
break. switch { ... }without an expression = a more readableif/else ifchain.- Init statement:
switch x := f(); { ... }, scope limited to the block. fallthroughexists but is rare; enters the next case WITHOUT evaluating its condition.- Type switch
v := i.(type)to discriminate based on the dynamic type (Interfaces module).