Sobes.tech
Junior

How can you check the type of an interface in Go?

sobes.tech AI

Answer from AI

In Go, to check the type of an interface, the common methods are type assertion and type switch.

If you have a variable of interface type, for example var i interface{}, and want to check if it implements a specific interface or is a specific type, you can do:

if v, ok := i.(MyInterface); ok {
    // i implements MyInterface, v is the asserted type
}

For checking multiple types, it is convenient to use type switch:

switch v := i.(type) {
case MyInterface:
    // i implements MyInterface
case *MyStruct:
    // i is a pointer to MyStruct
default:
    // other type
}

If you need to check the type more dynamically, you can use the reflect package:

import "reflect"

t := reflect.TypeOf(i)
if t.Implements(reflect.TypeOf((*MyInterface)(nil)).Elem()) {
    // i implements MyInterface
}

Thus, for simple cases, type assertion or type switch is enough; for more complex cases, reflection is used.