获取基于原始类型的类型的 reflect.Kind
Get the reflect.Kind of a type which is based on a primitive type
我想将 reflect.Kind 作为实现接口但其实现基于原始类型的类型的 reflect.Interface:type id string
另一种答案可能是如何在调用 Kind() 时获得 returns reflect.Interface 的任何类型的 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()
(and reflect.ValueOf()
) 期望 interface{}
。基本上无论你传递给 reflect.TypeOf()
的值是什么,如果它还不是一个接口值,它将被隐式地包装在 interface{}
中。如果传递的值已经是接口值,那么存储在其中的具体值将作为 interface{}
.
传递
为了避免这种“重新包装”,这是一种罕见的情况,当指向接口的指针有意义时,实际上您无法在这里避免它。您必须传递一个指向接口值的指针。
因此,如果您将指针传递给接口,该指针将包含在 interface{}
值中。你可以使用Type.Elem()
得到“指向类型”的类型描述符:即指针类型的元素类型,这将是你要查找的接口类型的类型描述符。
示例:
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
参见相关问题:
我想将 reflect.Kind 作为实现接口但其实现基于原始类型的类型的 reflect.Interface:type id string
另一种答案可能是如何在调用 Kind() 时获得 returns reflect.Interface 的任何类型的 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()
(and reflect.ValueOf()
) 期望 interface{}
。基本上无论你传递给 reflect.TypeOf()
的值是什么,如果它还不是一个接口值,它将被隐式地包装在 interface{}
中。如果传递的值已经是接口值,那么存储在其中的具体值将作为 interface{}
.
为了避免这种“重新包装”,这是一种罕见的情况,当指向接口的指针有意义时,实际上您无法在这里避免它。您必须传递一个指向接口值的指针。
因此,如果您将指针传递给接口,该指针将包含在 interface{}
值中。你可以使用Type.Elem()
得到“指向类型”的类型描述符:即指针类型的元素类型,这将是你要查找的接口类型的类型描述符。
示例:
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
参见相关问题: