Switch Type

A type switch is like a regular switch statement, but the cases specify types (not values) that are compared to the type of the value held by the given interface value.


switch v := i.(type) {
case string:
    fmt.Println(v)
case int:
    fmt.Println(v+2)
}
                        

The type assertion happens implicitly for the correct type at the time of defining the variable v. Remembering that using the i.(type) notation is only valid inside a switch.

switch_type.go