Go Type Assertion: Difference between revisions
Jump to navigation
Jump to search
Line 6: | Line 6: | ||
=Overview= | =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 [[Go_Interfaces#Interface_Values|here]] for the code used in the example). | 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 [[Go_Interfaces#Interface_Values|here]] for the code used in the example). | ||
<syntaxhighlight lang='go'> | <syntaxhighlight lang='go'> | ||
var i SomeInterface | var i SomeInterface = &SomeImplementation{"test"} | ||
v, ok := i.(*SomeImplementation) | v, ok := i.(*SomeImplementation) | ||
</syntaxhighlight> | </syntaxhighlight> | ||
Revision as of 23:26, 13 August 2024
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)
Type Assertion
Type Switch
A type switch is a new control structure introduced by Go.
Type assertion with switch
:
var i SomeInterface
i = TypeA{"A"}
switch v := i.(type) {
case TypeA:
fmt.Printf("TypeA: %v\n", v)
case TypeB:
fmt.Printf("TypeB: %v\n", v)
}