gpt4 book ai didi

go - 获取基于原始类型的类型的reflect.Kind

转载 作者:行者123 更新时间:2023-12-01 20:08:15 25 4
gpt4 key购买 nike

我想将reflect.Kind作为实现接口(interface)的类型的reflect.Interface,但其实现基于原始类型:type id string

对此问题的另一种答案可能是如何在调用 Kind() 时获取返回reflect.Interfaces 的任何类型的reflect.Type。

这是 Go Playground 的完整示例:

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())
}

最佳答案

reflect.TypeOf() (和 reflect.ValueOf() )需要一个接口(interface){}。基本上,无论您传递给 reflect.TypeOf() 的值是什么,如果它还不是接口(interface)值,它都会隐式包装在 interface{} 中。如果传递的值已经是接口(interface)值,则其中存储的具体值将作为接口(interface){}传递。

为了避免这种“重新打包”,这是指向接口(interface)的指针有意义的罕见情况之一,事实上您在这里无法避免它。您必须传递一个指向接口(interface)值的指针。

因此,如果您将指针传递给接口(interface),则该指针将被包装在 interface{} 值中。您可以使用 Type.Elem() 来获取“指向类型”的类型描述符:即指针类型的元素类型,它将是您的接口(interface)类型的类型描述符正在寻找。

示例:

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

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

fmt.Println(t.Kind())

哪个输出(在 Go Playground 上尝试一下):

test
main.ID
interface

查看相关问题:What is the difference between reflect.ValueOf() and Value.Elem() in go?

关于go - 获取基于原始类型的类型的reflect.Kind,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63938572/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com