Back in December we looked at type assertions, which allow us to assert whether an interface type is of a specific underlying type. In that conversation, I promised we’d get to the more flexible type switches. And now, at long last, we have arrived!
Type switches
A type switch compares types rather than values. It is otherwise similar to an expression switch. It is marked by a special switch expression that has the form of a type assertion using the keyword type rather than an actual type:
switch x.(type) { // cases }
When looking at switch statements, we looked at equivalent if-else
blocks and switch statements. Let’s introduce type switches with a similar example comparison, before diving into the details tomorrow. These two code snippets are equivalent:
if _, ok := x.(int) {
/* ... */
} else if _, ok := x.(float64) {
/* ... */
} else if _, ok := x.(string) {
/* ... */
}
and
switch x.(type) {
case int:
/* ... */
case float64:
/* ... */
case string:
/* ... */
}
Quotes from The Go Programming Language Specification Language version go1.22 (Feb 6, 2024)