Go Type Switch

From NovaOrdis Knowledge Base
Jump to navigation Jump to search

Internal

Overview

A type switch is a new control structure introduced by Go and a generalization of the type assertion. While a type assertion checks whether a specific concrete type implements a given interface, the type switch generalizes this check for multiple options, helping with the discovery of the dynamic type for an interface variable. The type switch uses the syntax of the type assertion with the keyword type inside the parentheses.

var t SomeInterface = &SomeImplementation{data: "test"}
	
switch t := t.(type) { // it is idiomatic to reuse the variable name, but this in effect declares
                       // a new variable with the same name but a different type in each case
case *SomeImplementation:
	...
case *SomeImplementationB:
	...
}