为什么在 Go 中将指针放在 interface{} 中会导致 reflect 丢失类型名称?

Why does putting a pointer in an interface{} in Go cause reflect to lose the name of the type?

下面的示例显示了当您反思设置为对象 (g) 和指向所述对象 (h) 的指针的接口 {} 时会发生什么。这是设计使然,我是否应该期望我的数据类型丢失或者更确切地说,或者当我将指针放入接口 {} 时我无法取回数据类型的名称?

包主

导入 "fmt"
导入 "reflect"

输入 Foo 结构 {
    条串
}

功能主要(){
    f := Foo{Bar: "FooBar"}
    类型名称 := reflect.TypeOf(f).名称()
    fmt.Printf("typeName %v\n", 类型名称)

    变量接口{}
    g = f
    typeName = reflect.TypeOf(g).Name()
    fmt.Printf("typeName %v\n", 类型名称)

    变量 h 接口{}
    h = &f
    typeName = reflect.TypeOf(h).Name()
    fmt.Printf("typeName %v\n", 类型名称)
}

输出:

类型名称 Foo
类型名称 Foo
类型名称

也位于:

http://play.golang.org/p/2QuBoDxHfX

正如 Name 方法的文档所说,未命名类型将 return 一个空字符串:

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"