Skip to main content
eLearner.app
Module 2 · Lesson 4 of 59/50 in the course~10 min
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

Go
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:

Go
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:

Go
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:

Go
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:

Go
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

Exercise#go.m2.l4.e1
Attempts: 0Loading…

Print 'feriale' for lun/mar/mer/gio/ven, 'weekend' otherwise, using a switch on the value of g.

Loading editor…
Show hint

Group the 5 weekdays into a single case separated by commas.

Solution available after 3 attempts

Exercise#go.m2.l4.e2
Attempts: 0Loading…

Use a switch WITHOUT a condition to print 'neg', 'zero' or 'pos' depending on x.

Loading editor…
Show hint

No expression after `switch`, just `{`.

Solution available after 3 attempts

Quiz#go.m2.l4.e3
Ready

What does this program print?

Go
switch 1 {
case 1:
    fmt.Print("a")
case 2:
    fmt.Print("b")
}
Answer options

Recap

  • case accepts multiple values separated by commas.
  • No implicit fallthrough: each case has its own implicit break.
  • switch { ... } without an expression = a more readable if/else if chain.
  • Init statement: switch x := f(); { ... }, scope limited to the block.
  • fallthrough exists 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).