下面的示例显示了当您反射(reflection)设置为对象 (g) 和指向所述对象 (h) 的指针的接口(interface) {} 时会发生什么。这是设计使然,当我将指针放入接口(interface) {} 时,我是否应该期望我的数据类型丢失或者更确切地说我无法取回数据类型的名称?
package main import "fmt" import "reflect" type Foo struct { Bar string } func main() { f := Foo{Bar: "FooBar"} typeName := reflect.TypeOf(f).Name() fmt.Printf("typeName %v\n", typeName) var g interface{} g = f typeName = reflect.TypeOf(g).Name() fmt.Printf("typeName %v\n", typeName) var h interface{} h = &f typeName = reflect.TypeOf(h).Name() fmt.Printf("typeName %v\n", typeName) }
输出:
typeName Foo typeName Foo typeName
同时在:
最佳答案
正如 Name
方法的文档所说,未命名的类型将返回一个空字符串:
Name
returns the type's name within its package. It returns an empty string for unnamed types.
h
的类型是未命名的指针类型,其元素类型是已命名的结构类型 Foo
:
v := reflect.TypeOf(h)
fmt.Println(v.Elem().Name()) // prints "Foo"
如果您想要像这样的复杂未命名类型的标识符,请使用 String
方法:
fmt.Println(v.String()) // prints "*main.Foo"
关于pointers - 为什么在 Go 中将指针放在 interface{} 中会导致 reflect 丢失类型名称?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28338600/