How to get real type of pointer with reflect?

4,996 views
Skip to first unread message

Hoping White

unread,
Dec 5, 2011, 5:17:29 AM12/5/11
to golan...@googlegroups.com

Hi, all       

        

         package main

 

import (

    //"unicode"

    "reflect"

)

 

 

type T1 struct {

    Name string

}

 

 

func main() {

    t2 := make(map[string]*T1)

    t := reflect.TypeOf(t2)

    println(t.Elem().String())

}

 

 

As the above code shows, then I have two question,

 

1.       Is it possbile to get a reflect.Type without a value? Or the reflect.TypeOf is the only way?

2.       t.Elem returns a reflect.Ptr, how can I get the reflect.Type this pointer pointed to ?

 

Thanks !

David Symonds

unread,
Dec 5, 2011, 6:27:12 AM12/5/11
to Hoping White, golan...@googlegroups.com
On Mon, Dec 5, 2011 at 9:17 PM, Hoping White <baiha...@gmail.com> wrote:

> 1.       Is it possbile to get a reflect.Type without a value? Or the
> reflect.TypeOf is the only way?

No, you need at least a zero value of the type, or a more complex type
that embeds it (e.g. *T, chan T, map[int]T).

> 2.       t.Elem returns a reflect.Ptr, how can I get the reflect.Type this
> pointer pointed to ?

Call Elem again: t.Elem().Elem().

If all you want is the reflect.Type of T1,
t := reflect.TypeOf((*T1)(nil)).Elem()
That takes the zero value of *T, gets its reflect.Type, and then takes
its element type.


Dave.

Reply all
Reply to author
Forward
0 new messages