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