what’s type assertion in Go
tags: learning programming go
content
- to check if a go type has an interface, we could do:
- could be struct or non-struct type, as long as it’s a type
- which means interface is also included!
value, ok := interface_var.(TypeName)- example:
var x any
x = 10
value, ok := x.(int)
fmt.Println(value, ok) // 10, true
value, ok := x.(string)
fmt.Println(value, ok) // "", false
str := x.(string) // PANIC!- another example:
type MyType string
func checkType (a any) {
b, ok := a.(MyType)
}- if
ais the type ofMyType,bgets the value and type ofa - if
ais a different type thanMyType,bbecomes zero value ofMyType(MyType{})