flâneur — a map of the web's best reading

Golang Type Assertion Explained with Examples | GoLinuxCloud

golinuxcloud.com · 2,126 words · saved by 1 readers

Golang type assertion is a mechanism for working with the underlying concrete value of an interface. Type switches use switch blocks for data types and allow you to differentiate between type assertion values, which are data types, and process each data type the way you want. On the other hand, in order to use the empty interface in type switches, you need to use type assertions.

Type assertion is how you recover the concrete value stored inside an interface value, or test whether the dynamic type implements another interface. It is easy to confuse with type conversion ( T(x) ), which rewrites compatible concrete values. This page walks through syntax, the comma-ok idiom, panics, type switches, and when you do not need assertion at all. For the broader interface model, see interfaces in Go . For JSON decoding into map[string]any and similar shapes, see JSON unmarshal in Go . Tested on: Go 1.22, 64-bit Linux. Single-result x.(T) panics if the dynamic type does not match

Explore this link on the map →

related reading