Go Type Switch: Difference between revisions
Jump to navigation
Jump to search
No edit summary |
|||
Line 5: | Line 5: | ||
=Overview= | =Overview= | ||
A type switch is a new [[Go_Language#Type_Switch|control structure]] introduced by Go. | A type switch is a new [[Go_Language#Type_Switch|control structure]] introduced by Go and a generalization of the [[Go_Type_Assertion#Overview|type assertion]]. While a type assertion checks whether a specific [[Go_Language#Concrete_vs._Interface_Types|concrete type]] implements a given interface, the type switch generalizes this check for multiple options: | ||
<syntaxhighlight lang='go'> | <syntaxhighlight lang='go'> | ||
var i SomeInterface | var i SomeInterface = &SomeImplementation{data: "test"} | ||
switch v := i.(type) { | switch v := i.(type) { | ||
case *SomeImplementation: | |||
... | |||
case *SomeImplementationB: | |||
... | |||
} | } | ||
</syntaxhighlight> | </syntaxhighlight> |
Revision as of 16:39, 14 August 2024
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:
var i SomeInterface = &SomeImplementation{data: "test"}
switch v := i.(type) {
case *SomeImplementation:
...
case *SomeImplementationB:
...
}