英文:
Why does putting a pointer in an interface{} in Go cause reflect to lose the name of the type?
问题
下面的示例展示了当你对设置为对象(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
也可以在以下链接中查看:
http://play.golang.org/p/2QuBoDxHfX
英文:
The example below shows what happens when you reflect on an interface {} that is set to an object (g) and a pointer to said object (h). Is this by design, should I expect that my datatype is lost or rather or that I cannot get name of the datatype back when I put my pointer in an interface {}?
<pre>
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)
}
</pre>
Outputs:
<pre>
typeName Foo
typeName Foo
typeName
</pre>
Also at:
答案1
得分: 8
根据Name
方法的文档,未命名的类型将返回一个空字符串:
Name
方法返回类型在其包中的名称。
对于未命名的类型,它返回一个空字符串。
变量h
的类型是一个未命名的指针类型,其元素类型是命名的结构体类型Foo
:
v := reflect.TypeOf(h)
fmt.Println(v.Elem().Name()) // 输出 "Foo"
如果你想要一个复杂未命名类型的标识符,可以使用String
方法:
fmt.Println(v.String()) // 输出 "*main.Foo"
英文:
As the Name
method's documentation says, unnamed types will return an empty string:
> Name
returns the type's name within its package.
> It returns an empty string for unnamed types.
The type of h
is an unnamed pointer type whose element type is the named struct type Foo
:
v := reflect.TypeOf(h)
fmt.Println(v.Elem().Name()) // prints "Foo"
If you want an identifier for complex unnamed types like this, use the String
method:
fmt.Println(v.String()) // prints "*main.Foo"
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论