我想将 reflect.Kind 作为 reflect.Interface 的类型,用于实现接口但其实现基于原始类型的类型:type id string对此的替代答案可能是如何获得在调用 Kind() 时返回 reflect.Interfaces 的任何类型的 reflect.Type。这是Go Playground上的完整示例:type ID interface { myid()}type id stringfunc (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())}
1 回答

慕的地6264312
TA贡献1817条经验 获得超6个赞
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
- 1 回答
- 0 关注
- 151 浏览
添加回答
举报
0/150
提交
取消