Retrieving the reflect.Kind of a Type Based on a Primitive Type
In Go, you can use the reflect package to inspect the structure of types and values. However, determining the reflect.Kind of a type that implements an interface but is based on a primitive type can be challenging.
Consider the following example:
type ID interface { myid() } type id string func (id) myid() {}
Here, the id type implements the ID interface, but its implementation is based on the primitive type string. When you attempt to get the reflect.Kind of id using reflect.TypeOf(id).Kind(), it will return reflect.String instead of reflect.Interface.
To resolve this issue, you need to pass a pointer to the interface value instead of the value itself. The reason is that reflect.TypeOf() expects interface values, but if a non-interface value is passed, it will be wrapped in an interface{} implicitly.
Here's an example:
id := ID(id("test")) fmt.Println(id) t := reflect.TypeOf(&id).Elem() fmt.Println(t) fmt.Println(t.Kind())
The output is:
test main.ID interface
In this case, reflect.TypeOf(&id) returns a pointer to the interface value, which is then "unwrapped" using t := reflect.TypeOf(&id).Elem(). The resulting t is the type descriptor of the ID interface, and its Kind() method returns reflect.Interface.
This approach can be used to get the reflect.Kind of any type that returns reflect.Interfaces when calling Kind(), even if it is based on a primitive type.
The above is the detailed content of How to Get the Correct reflect.Kind of a Primitive Type Implementing an Interface in Go?. For more information, please follow other related articles on the PHP Chinese website!