In Go, how do I check a value is of (any) pointer type?

12,528

You can use reflection (reflect package) to test if a value is of pointer type.

func firstPointerIdx(s []interface{}) int {
    for i, v := range s {
        if reflect.ValueOf(v).Kind() == reflect.Ptr {
            return i
        }
    }
    return -1
}

Note that the above code tests the type of the value that is "wrapped" in an interface{} (this is the element type of the s slice parameter). This means if you pass a slice like this:

s := []interface{}{"2", nil, (*string)(nil)}

It will return 2 because even though 3rd element is a nil pointer, it is still a pointer (wrapped in a non-nil interface value).

Share:
12,528
Elad
Author by

Elad

Updated on June 18, 2022

Comments

  • Elad
    Elad almost 2 years

    I have a slice of interface{} and I need to check whether this slice contains pointer field values.

    Clarification example:

    var str *string
    s := "foo"
    str = &s
    var parms = []interface{}{"a",1233,"b",str}
    index := getPointerIndex(parms)
    fmt.Println(index) // should print 3
    
  • Elad
    Elad about 8 years
    Exactly what I was looking for, Thanks!