Home > Backend Development > Golang > How to Determine the `reflect.Kind` of a Derived Interface Type in Go?

How to Determine the `reflect.Kind` of a Derived Interface Type in Go?

Susan Sarandon
Release: 2025-01-02 12:34:40
Original
345 people have browsed it

How to Determine the `reflect.Kind` of a Derived Interface Type in Go?

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())
}
Copy after login

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())
Copy after login

This code will output:

test
main.ID
interface
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template