liveBook · Manning

Type switch

As explained in Go in Practice, Second Edition

A type switch statement is a Go control-flow construct that selects a case according to the dynamic type of an interface value.

A type switch selects a branch according to the dynamic type stored in an interface value. It suits functions that accept arbitrary values and need type-specific processing, such as converting numeric and string inputs before summing them. Write the switch as `switch val.(type)` and handle each supported type in its own case. section 13.1.1

Summing mixed values

A variadic `sum(v ...interface{}) float64` can range over its arguments and switch on each value's type. The example handles `int`, `int64`, `uint8`, and `string`; numeric values are converted to `float64`, while strings are parsed with `strconv.ParseFloat`. Calling `sum(a, b, c)` with `uint8(2)`, `int(37)`, and `"3.2"` produces `42.200000`. A `default` branch can report and ignore unsupported values. A named type such as `MyInt int64` does not match the `int64` case, so the example prints an unsupported-type message and leaves it out. section 13.1.1

Type switches differ from ordinary value switches: combining several types in one case complicates the value assigned inside that case, so one type per case is typical. When matching by underlying kind is more important than matching an exact type, reflection provides an alternative: `reflect.ValueOf(val).Kind()` can group `reflect.Int` and `reflect.Int64`, and named integer types then participate in the same branch. section 13.1.1

How Go in Practice, Second Edition covers it

How deep it goes
Explains syntax, conversions, parsing, unsupported types, named-type behavior, and the reflection-based kind-switch alternative.
Examples
Demonstrates a variadic mixed-value sum, string parsing, a named MyInt type, unsupported-type output, and a reflect-based kind switch.
What it assumes
Assumes basic Go functions, interfaces, switches, conversions, and error handling; clarifies type inspection from the example.
What you can do after
Builds generic Go functions that process supported interface values and choose exact-type or underlying-kind dispatch.
How it connects
Connects interfaces, switch statements, type conversion, reflection, reflect.Type, and reflect.Kind.

Also explained in

Compare how 2 books explain type switch →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Go in Practice, Second Edition. The section links point to the parts of the book it draws on.