Go Type Assertion: Difference between revisions
Jump to navigation
Jump to search
No edit summary |
|||
Line 53: | Line 53: | ||
</syntaxhighlight> | </syntaxhighlight> | ||
=Type Assertion= | |||
=Type Switch= | |||
Type assertion with <code>switch</code>: | Type assertion with <code>switch</code>: | ||
<syntaxhighlight lang='go'> | <syntaxhighlight lang='go'> |
Revision as of 21:14, 27 December 2023
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:
var i SomeInterface
v, isType := i.(TypeName)
Usage example:
type SomeInterface interface {
MethodA()
}
type TypeA struct {
s string
}
func (v *TypeA) MethodA() {
fmt.Println("TypeA.MethodA()")
}
type TypeB struct {
s string
}
func (v *TypeB) MethodA() {
fmt.Println("TypeB.MethodA()")
}
...
var i SomeInterface
i = &TypeA{"A"}
b := &TypeB{"B"}
a, isTypeA := i.(*TypeA)
fmt.Printf("%v, %t\n", a, isTypeA) // will print {A}, true
b, isTypeB := i.(*TypeB)
fmt.Printf("%v, %t\n", b, isTypeB) // will print <nil>, false
Type Assertion
Type Switch
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)
}