Nat*_*ate 6 reflection pointers go
下面的示例显示了当您反映设置为对象(g)的接口{}和指向所述对象(h)的指针时发生的情况.这是设计,我应该期望我的数据类型丢失或者更确切地说,或者当我将指针放在接口{}中时,我无法获得数据类型的名称?
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返回其包中的类型名称.它为未命名的类型返回一个空字符串.
类型h是未命名的指针类型,其元素类型是命名的结构类型Foo:
v := reflect.TypeOf(h)
fmt.Println(v.Elem().Name()) // prints "Foo"
Run Code Online (Sandbox Code Playgroud)
如果您想要这样的复杂未命名类型的标识符,请使用以下String方法:
fmt.Println(v.String()) // prints "*main.Foo"
Run Code Online (Sandbox Code Playgroud)