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

1

24

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
Girosol answered 27/4, 2016 at 13:13 Comment(2)
*str will dereference the pointer and it will be of nonpointer string type. Did you mean to put str into the slice literal?Devonne
yep, didn't noticed, edited.Girosol
D
38

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).

Devonne answered 27/4, 2016 at 13:19 Comment(1)
Exactly what I was looking for, Thanks!Girosol

© 2022 - 2024 — McMap. All rights reserved.