Go Type Assertion
Jump to navigation
Jump to search
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).
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