Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 439
Nate Avatar asked Feb 05 '15 07:02

Nate


People also ask

Is interface a pointer Golang?

Go's interface values are really a pair of pointers. When you put a concrete value into an interface value, one pointer starts pointing at the value. The second will now point to the implementation of the interface for the type of the concrete value.

Does Golang have reflection?

Reflection is the ability of a program to introspect and analyze its structure during run-time. In Go language, reflection is primarily carried out with types. The reflect package offers all the required APIs/Methods for this purpose.

How does Golang reflection work?

Every type in golang, including user-defined type, itself has the information about type name, fields name and the function name. Golang reflection just reads these information or call the function. Through some mechanism, Golang can get the type name, storage size and so on.

What is reflect value Golang?

The reflect. ValueOf() Function in Golang is used to get the new Value initialized to the concrete value stored in the interface i. To access this function, one needs to imports the reflect package in the program.


1 Answers

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"
like image 133
James Henstridge Avatar answered Apr 27 '23 05:04

James Henstridge