Go Type Switch: Difference between revisions

From NovaOrdis Knowledge Base
Jump to navigation Jump to search
(Created page with "=Internal= =Overview= A type switch is a new control structure introduced by Go. Type assertion with <code>switch</code>: <syntaxhighlight lang='go'> 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) } </syntaxhighlight>")
 
 
(6 intermediate revisions by the same user not shown)
Line 1: Line 1:
=Internal=
=Internal=
* [[Go_Interfaces#Type_Switch|Go Interfaces]]
* [[Go_Type_Assertion#Overview|Type Assertion]]
=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, helping with the discovery of the [[Go_Interfaces#Dynamic_Type|dynamic type]] for an interface variable. The type switch uses the syntax of the type assertion with the keyword <code>[[Go_Language#type_keyword|type]]</code> inside the parentheses.


Type assertion with <code>switch</code>:
<syntaxhighlight lang='go'>
<syntaxhighlight lang='go'>
var i SomeInterface
var t SomeInterface = &SomeImplementation{data: "test"}
i = TypeA{"A"}
 
switch t := t.(type) { // it is idiomatic to reuse the variable name, but this in effect declares
switch v := i.(type) {
                      // a new variable with the same name but a different type in each case
  case TypeA:
case *SomeImplementation:
fmt.Printf("TypeA: %v\n", v)
...
  case TypeB:
case *SomeImplementationB:
fmt.Printf("TypeB: %v\n", v)
...
}
}
</syntaxhighlight>
</syntaxhighlight>

Latest revision as of 16:46, 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, 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:
	...
}