Home > Backend Development > Golang > How to Retrieve `reflect.Kind.Interface` for a Type Implementing an Interface Based on a Primitive Type in Go?

How to Retrieve `reflect.Kind.Interface` for a Type Implementing an Interface Based on a Primitive Type in Go?

Barbara Streisand
Release: 2024-12-31 05:30:12
Original
606 people have browsed it

How to Retrieve `reflect.Kind.Interface` for a Type Implementing an Interface Based on a Primitive Type in Go?

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

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

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

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!

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