Retrieving reflect.Kind for a Type Based on a Primitive Type
In Go, determining the reflect.Kind of a type can be tricky when the type implements an interface based on a primitive type. For instance, consider the following scenario:
type ID interface { myid() } type id string func (id) myid() {} func main() { id := ID(id("test")) fmt.Println(id) fmt.Println(reflect.TypeOf(id)) // How to get the kind to return "reflect.Interface" from the var "id"? fmt.Println(reflect.TypeOf(id).Kind()) }
In this example, the ID interface is implemented by the id type, which is based on the primitive string type. While we want reflect.TypeOf(id).Kind() to return reflect.Interface, it instead returns reflect.String.
Solution using Pointer to Interface
To resolve this issue, we need to remember that reflect.TypeOf() expects an interface{}. When working with non-interface values, Go automatically wraps them in an interface{} implicitly. To avoid this, we can use a pointer to the interface.
t := reflect.TypeOf(&id).Elem() fmt.Println(t.Kind())
By using reflect.TypeOf(&id).Elem(), we retrieve the type descriptor of the ID interface, which is what we are interested in. The Elem() method gives us the element type of the pointer type, which is the interface type.
Running the updated code will now output:
test main.ID interface
This demonstrates how to correctly obtain the reflect.Kind for a type that implements an interface based on a primitive type.
The above is the detailed content of How to Retrieve `reflect.Kind.Interface` for a Type Implementing an Interface Based on a Primitive Type in Go?. For more information, please follow other related articles on the PHP Chinese website!