liveBook · Manning

Type assertion

As explained in Go in Action, Second Edition

A type assertion is a Go operation that checks whether an interface value contains a specified concrete type and retrieves the contained value if it does.

A type assertion checks whether an interface value contains a specified concrete type and retrieves that value when the check succeeds. It is useful when abstract interface-based code needs type-specific behavior or additional concrete data. section 5.6

Use the comma-ok form when a failed assertion should be handled explicitly:

  • Write value, ok := iface.(ConcreteType). A successful assertion sets ok to true and provides the concrete value; an unsuccessful assertion sets ok to false. section 5.6
  • Choose a type switch instead when several concrete types require different handling. section 5.6
  • With generic interfaces, assert only to a matching instantiation: the compiler rejects an impossible type such as *LinkedList[string] before runtime. section 6.5.3

Inspecting a measurement

if mw, ok := m.(MetricWeight); ok { fmt.Println("MetricWeight magnitude:", mw.Magnitude) } Here, m remains usable through its interface while mw exposes MetricWeight-specific data after a successful assertion. section 5.6

How Go in Action, Second Edition covers it

How deep it goes
Explains comma-ok results, contrasts type switches, and covers exact generic-instantiation checks without broader runtime internals.
Examples
Uses MetricWeight inspection, measurement-system classification, and Collection[int] assertions to illustrate concrete-type handling.
What it assumes
Assumes familiarity with interfaces and concrete implementations while reinforcing runtime type checking and interface-based abstraction.
What you can do after
Apply it via comma-ok assertions for one concrete type and type switches for several possible interface implementations.
How it connects
Connects interfaces, concrete types, type switches, generics, and type parameters.

Also explained in

Compare how 5 books explain type assertion →

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.