首页 >后端开发 >Golang >如何在 Go 中获取实现接口的正确的原始类型的reflect.Kind?

如何在 Go 中获取实现接口的正确的原始类型的reflect.Kind?

Patricia Arquette
Patricia Arquette原创
2024-12-17 04:58:24399浏览

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

检索基于原始类型的reflect.Kind类型

在Go中,您可以使用reflect包来检查结构类型和值。然而,确定实现接口但基于原始类型的类型的reflect.Kind可能具有挑战性。

考虑以下示例:

type ID interface {
    myid()
}

type id string

func (id) myid() {}

这里,id类型实现了ID接口,但是它的实现是基于原始类型string的。当您尝试使用reflect.TypeOf(id).Kind()获取id的reflect.Kind时,它将返回reflect.String而不是reflect.Interface。

要解决此问题,您需要通过指向接口值而不是值本身的指针。原因是reflect.TypeOf()需要接口值,但如果传递非接口值,它将隐式包装在interface{}中。

下面是一个示例:

id := ID(id("test"))

fmt.Println(id)
t := reflect.TypeOf(&id).Elem()
fmt.Println(t)

fmt.Println(t.Kind())

输出为:

test
main.ID
interface

在这种情况下,reflect.TypeOf(&id) 返回一个指向接口值的指针,然后使用 t :=reflect.TypeOf(&id).Elem()“展开”。得到的t是ID接口的类型描述符,其Kind()方法返回reflect.Interface。

调用时可以使用此方法获取任何返回reflect.Interfaces的类型的reflect.Kind Kind(),即使它基于原始类型。

以上是如何在 Go 中获取实现接口的正确的原始类型的reflect.Kind?的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn