Reflection type.Name() weirdness

3,565 views
Skip to first unread message

tomwilde

unread,
Mar 13, 2012, 5:44:44 PM3/13/12
to golan...@googlegroups.com
Please see the following small piece of code:

http://weekly.play.golang.org/p/Ih8CbOFeZ8

Why am I not getting the name of the type?

According to documentation (http://weekly.golang.org/pkg/reflect/#Type):

// Name returns the type's name within its package.
// It returns an empty string for unnamed types.

... but this type is not unnamed



------- Code for lazy people below -------

package main

import(
"fmt"
"reflect"
)

type Foo struct{}

func main() {
t := reflect.TypeOf(&Foo{})
fmt.Printf("Type's name is: %#v\n", t.Name())
}

minux

unread,
Mar 13, 2012, 5:55:02 PM3/13/12
to tomwilde, golan...@googlegroups.com
http://weekly.play.golang.org/p/rDpXgofwSl

package main

import(
"fmt"
"reflect"
)

type Foo struct{}

func main() {
t := reflect.TypeOf(&Foo{}).Elem()

tomwilde

unread,
Mar 13, 2012, 5:57:34 PM3/13/12
to golan...@googlegroups.com
Thank you

Rémy Oudompheng

unread,
Mar 13, 2012, 5:57:54 PM3/13/12
to tomwilde, golan...@googlegroups.com
Le 13 mars 2012 22:44, tomwilde <sedevel...@gmail.com> a écrit :
> Please see the following small piece of code:
>
> http://weekly.play.golang.org/p/Ih8CbOFeZ8
>
> Why am I not getting the name of the type?
>
> According to documentation (http://weekly.golang.org/pkg/reflect/#Type):
>
> // Name returns the type's name within its package.
> // It returns an empty string for unnamed types.
>
> ... but this type is not unnamed

Yes, it's unnamed, it's "pointer to Foo". If you expected Foo, do as
minux suggests, otherwise, try the String() method, it may suit your
needs.

fmt.Printf("Type of v is: %s", reflect.TypeOf(v))

and for display purposes, fmt.Printf("v has type %T", v) already does
it for you.

Rémy.

Reply all
Reply to author
Forward
0 new messages