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 a is the type of MyType, b gets the value and type of a
  • if a is a different type than MyType, b becomes zero value of MyType (MyType{})

up

down

reference