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
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.
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.
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.
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.
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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With