Type Assertions and Type Switches
Let’s learn about type assertions and type switches in Go.
A type assertion is a mechanism for working with the underlying concrete value of an interface. This mainly happens because interfaces are virtual data types without their own values—interfaces just define behavior and do not hold data of their own. But what happens when we do not know the data type before attempting a type assertion? How can we differentiate between the supported data types and the unsupported ones? How can we choose a different action for each supported data type? The answer is by using type switches.
Type switches
Type switches use switch
blocks for data types and allow us to differentiate between type assertion values, which are data types, and process each data type the way we want. On the other hand, in order to use the empty interface in type switches, we need to use type assertions.
Get hands-on with 1400+ tech skills courses.