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




