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

huangapple go评论92阅读模式
英文:

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(&quot;typeName %v\n&quot;, typeName)

var h interface{}
h = &amp;f
typeName = reflect.TypeOf(h).Name()
fmt.Printf(&quot;typeName %v\n&quot;, typeName)

}
</pre>

Outputs:

<pre>
typeName Foo
typeName Foo
typeName
</pre>

Also at:

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

答案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 &quot;Foo&quot;

If you want an identifier for complex unnamed types like this, use the String method:

fmt.Println(v.String()) // prints &quot;*main.Foo&quot;

huangapple
  • 本文由 发表于 2015年2月5日 15:41:07
  • 转载请务必保留本文链接:https://go.coder-hub.com/28338600.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定