liveBook · Manning

Type switch

As explained in Go in Action, Second Edition

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

A type switch is a Go control-flow construct that compares an interface value’s dynamic type with multiple cases. It supports type-specific logic while preserving an interface-based abstraction. section 5.6 section 5.0

Use a type switch when several concrete types require different handling. A single type assertion is more direct when only one concrete type matters; a default case can handle unexpected types. section 5.6

Classifying convertible measurements

A Convertible interface can contain metric or imperial measurements. The switch groups MetricWeight and MetricVolume under Metric, and ImperialWeight and ImperialVolume under Imperial, returning an empty value for unknown types. section 5.6

func MeasurementSystemFromConvertible(m Convertible) MeasurementSystem {
    switch m.(type) {#1
    case MetricWeight, MetricVolume:
        return Metric
    case ImperialWeight, ImperialVolume:
        return Imperial
    default:
        // Optionally handle unknown types
        return ""
    }
}

Inspect the complete function pattern for switching on a Convertible value and grouping several concrete types in one case. section 5.6

How Go in Action, Second Edition covers it

How deep it goes
Compares interface dynamic types and contrasts multiple-case switches with single-type assertions, but does not detail runtime internals.
Examples
Uses Convertible values with MetricWeight, MetricVolume, ImperialWeight, and ImperialVolume cases to select a measurement system.
What it assumes
Assumes interfaces and concrete types, while positioning runtime type checks alongside compile-time type safety.
What you can do after
Apply it via Go’s type-switch syntax to route interface values into type-specific logic.
How it connects
Connects interfaces, dynamic types, type assertions, concrete types, and Go’s type system.

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 Action, Second Edition. The section links point to the parts of the book it draws on.