Home >Backend Development >Golang >How to Get reflect.Interface Kind for a Go Type Based on a Primitive Type?

How to Get reflect.Interface Kind for a Go Type Based on a Primitive Type?

Barbara Streisand
Barbara StreisandOriginal
2024-12-25 08:43:09569browse

How to Get reflect.Interface Kind for a Go Type Based on a Primitive Type?

How to Obtain the reflect.Interface Kind for a Type Based on a Primitive Type

In Go, when working with types that implement interfaces but rely on primitive types in their implementation, it becomes necessary to obtain the reflect.Kind as a reflect.Interface. This article addresses this need and provides a solution.

The Problem

Consider the following situation:

Here, ID is an interface implemented by id, which is a string. When we use reflect.TypeOf(id) to obtain the type descriptor, the result is not the desired reflect.Interface but instead a reflect.String.

The Solution

To work around this issue, it is necessary to pass a pointer to the interface value instead of the value itself to reflect.TypeOf(). This prevents the implicit wrapping of the value in an interface{}.

In this example, reflect.TypeOf(&id) returns a pointer to the interface value, which is then unwrapped using Elem() to obtain the type descriptor of the interface itself. This approach provides the desired reflect.Interface Kind.

Additional Note

The same technique can be used to obtain any type of reflect.Type that returns reflect.Interface when calling Kind(). Simply pass a pointer to the value or type to reflect.TypeOf().

The above is the detailed content of How to Get reflect.Interface Kind for a Go Type Based on a Primitive Type?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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