determining underlying numeric pointer type with reflect

139 views
Skip to first unread message

Davis Ford

unread,
Oct 2, 2015, 4:26:16 PM10/2/15
to golang-nuts
I need to determine if something is of type pointer to int, *int, which happens to be a field of a struct.

I'm trying to figure out the best way -- wondering if someone has a quick suggestion.

given a Value type: 

var whatIsIt interface{} // passed in


type
:= reflect.TypeOf(whatIsIt)


for i := 0; i < typ.NumField(); i++ {
  f
:= typ.Field(i)


 
if f.Type.Kind() == reflect.Ptr {
     
var num int
     
if f.Type.AssignableTo(reflect.ValueOf(&num).Type()) {

        fmt
.Println("it is a pointer to int")
     
}
 
}
}

This seems a bit obtuse -- but I welcome any better suggestions. 

Ian Lance Taylor

unread,
Oct 2, 2015, 5:37:17 PM10/2/15
to Davis Ford, golang-nuts
Would it work to simply write f.Type.Elem().Kind() == reflect.Int ?

Ian

Davis Ford

unread,
Oct 2, 2015, 5:43:34 PM10/2/15
to Ian Lance Taylor, golang-nuts
Seems like that would work, plugging it in.  Is there any issue calling Type.Elem().Kind() if the pointer is nil?

Ian Lance Taylor

unread,
Oct 2, 2015, 6:36:21 PM10/2/15
to Davis Ford, golang-nuts
On Fri, Oct 2, 2015 at 2:43 PM, Davis Ford <davi...@gmail.com> wrote:
> Seems like that would work, plugging it in. Is there any issue calling
> Type.Elem().Kind() if the pointer is nil?

No, Type.Elem() only refers to the type, not the value. Even if the
value of a *int is nil, the type *int still has an element, which is
the type int.

Ian

Davis Ford

unread,
Oct 2, 2015, 6:42:23 PM10/2/15
to golang-nuts, davi...@gmail.com
Cool, thanks Ian!

Matt Harden

unread,
Oct 3, 2015, 11:02:48 AM10/3/15
to Davis Ford, golang-nuts
Do note that Type.Elem() will panic if the type's Kind is not Array, Chan, Map, Ptr, or Slice. If you have the original interface, why not just do `_, ok := whatIsIt.(*int)` ?

--
You received this message because you are subscribed to the Google Groups "golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Matt Harden

unread,
Oct 3, 2015, 11:05:04 AM10/3/15
to Davis Ford, golang-nuts
Oh, sorry ignore my email. I misunderstood the question.
Reply all
Reply to author
Forward
0 new messages