Determining the Kind of a Derived Interface Type in Go
Navigating the complexities of reflection in Go can be challenging, especially when dealing with derived interfaces and primitive types. In this article, we'll explore how to determine the reflect.Kind of a type that implements an interface but has an underlying primitive implementation.
The question arises from the following code snippet:
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 scenario, we have an interface called ID and a string type called id. However, the implementation of the id type employs the id string type. The goal is to retrieve the reflect.Kind as reflect.Interface from the id variable.
Solution
The key to solving this problem lies in understanding how reflection handles interface values. When passing a value to reflect.TypeOf(), it's automatically wrapped in an interface{}. However, to preserve the type information, one must use a pointer to the interface.
By defining a pointer to the ID interface and passing it to reflect.TypeOf(), we can obtain the type descriptor using Elem() to access the interface type's actual type descriptor.
Code Example
The following code snippet demonstrates the solution:
id := ID(id("test")) fmt.Println(id) t := reflect.TypeOf(&id).Elem() fmt.Println(t) fmt.Println(t.Kind())
This code will output:
test main.ID interface
By utilizing this technique, we can accurately determine the reflect.Kind of derived interface types and uncover their underlying implementation details.
The above is the detailed content of How to Determine the `reflect.Kind` of a Derived Interface Type in Go?. For more information, please follow other related articles on the PHP Chinese website!