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).
*str
will dereference the pointer and it will be of nonpointerstring
type. Did you mean to putstr
into the slice literal? – Devonne