Home > Backend Development > Golang > How to Get the Correct reflect.Kind of a Primitive Type Implementing an Interface in Go?

How to Get the Correct reflect.Kind of a Primitive Type Implementing an Interface in Go?

Patricia Arquette
Release: 2024-12-17 04:58:24
Original
398 people have browsed it

How to Get the Correct reflect.Kind of a Primitive Type Implementing an Interface in Go?

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

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

The output is:

test
main.ID
interface
Copy after login

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!

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