Nate
Nate

Reputation: 5407

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

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 {}?

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)
}

Outputs:

typeName Foo
typeName Foo
typeName 

Also at:

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

Upvotes: 10

Views: 1317

Answers (1)

James Henstridge
James Henstridge

Reputation: 43949

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"

Upvotes: 8

Related Questions