In Go, how can I check the value of a type of (any) pointer?

I have a fragment interface{}, and I need to check if this fragment 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
+4
source share
1 answer

You can use reflection ( reflect) to check if the pointer type matters.

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

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

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

2, nil, - ( nil).

+5

All Articles