Go Type Assertion
External
Internal
Overview
An interface hides the differences between the types implementing it and emphasizes the commonality. However, there are times you may want to know what exact concrete type exists behind the interface. Type assertions can be used for type disambiguation.
A type assertion is an expression that probes whether an interface is of a certain concrete type, and if it is, returns a variable of that type (see here for the code used in the example).
typedValue := interfaceValue.(typeName)
The typeName
must either be the concrete type held by the interface, or a second interface type that the value can be converted to.
Note that if the conversion cannot be made, the program will crash with a run-time error. To avoid the panic, use the "comma, ok" idiom:
typedValue, ok := interfaceValue.(typeName)
If the type assertion fails, ok
will be false
and the typed value variable will get the zero value of the type.
var i SomeInterface = &SomeImplementation{"test"}
v, ok := i.(*SomeImplementation)
The type assertion also works when the interface variable only carries a dynamic type, but not a dynamic value:
var i SomeInterface
var t *SomeImplementation
i = t
v, ok := i.(*SomeImplementation) // ok is true, v is nil, as there is no dynamic value
Type assertion is a form of type conversion. Type assertion is also a simplified case of type switch with just one clause. The type assertion syntax borrows from the clause opening a type switch, but with an explicit type rather than the type
keyword.