Skip to main content
eLearner.app
Module 6 · Lesson 3 of 528/50 in the course~10 min
Module lessons (3/5)

Type switch

A type switch discriminates among multiple possible types of an interface value. It's the generalization of comma ok when there are more than one case.

Syntax

Go
func describe(i interface{}) string {
    switch v := i.(type) {
    case int:
        return fmt.Sprintf("int %d", v)
    case string:
        return fmt.Sprintf("string %q", v)
    case nil:
        return "nil"
    default:
        return fmt.Sprintf("altro tipo: %T", v)
    }
}
  • i.(type) is a special syntax, valid ONLY inside switch.
  • v := ... binds the value with the current case's type: inside case int, v has type int.
  • default catches all other types; there v has the type of the original interface.
  • case nil matches the interface with a nil dynamic type.

"Nameless" case

If you don't need the typed value, you can omit the v:

Go
switch i.(type) {
case int:
    // you know it's an int, but you don't have a variable of that type
case string:
    // ...
}

A form used when you just need to discriminate the type, not operate on the value.

Multiple types in the same case

Go
switch v := i.(type) {
case int, int64:
    // here v is still interface{}: the "common" type is just the interface
    fmt.Println("numero intero:", v)
case string:
    // here v is string
    fmt.Println("stringa:", v)
}

Typical use case: formatted printing

Go
func print(i interface{}) {
    switch v := i.(type) {
    case int:
        fmt.Printf("%d\n", v)
    case string:
        fmt.Printf("%s\n", v)
    case fmt.Stringer:
        fmt.Println(v.String())
    default:
        fmt.Printf("%v\n", v)
    }
}

fmt.Println itself uses a type switch internally to handle the standard formats.

Type switch vs reflection

For a few known types → type switch (fast, readable). For dynamic inspection of unknown types → the reflect package (more powerful but slower and more verbose).

Try it

Exercise#go.m6.l3.e1
Attempts: 0Loading…

Implement describe(i interface{}) string that returns 'int', 'string' or 'altro' depending on the dynamic type.

Loading editor…
Show hint

Syntax: `switch i.(type) { case T: ... default: ... }`.

Solution available after 3 attempts

Exercise#go.m6.l3.e2
Attempts: 0Loading…

Write printVal(i interface{}) that uses v := i.(type) and prints with %d for int, %s for string.

Loading editor…
Show hint

Inside `case int`, v has type int (you can pass it to Printf).

Solution available after 3 attempts

Quiz#go.m6.l3.e3
Ready

Which syntax starts a type switch?

Go
switch ??? {
  case int: ...
}
Answer options

Recap

  • switch v := i.(type) { case T: ... }: discriminates on the dynamic type.
  • Inside a single-type case, v has the case's type.
  • case T1, T2: v keeps the original interface's type.
  • default for unhandled cases; case nil for the nil interface.
  • No fallthrough in type switches.
  • 1 type → type assertion; 2+ types → type switch.