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
The *int is a pointer to an integer value. The & is used to get the address (a pointer) to the variable. The * character is used to dereference a pointer -- it returns a value to which the pointer references.
The Pointer Type. The pointer type in Go is used to point to a memory address where data is stored. Similar to C/C++, Go uses the * operator to designate a type as a pointer. The following snippet shows several pointers with different underlying types.
Pointers in Go programming language or Golang is a variable that is used to store the memory address of another variable. Pointers in Golang is also termed as the special variables. The variables are used to store some data at a particular memory address in the system.
A pointer to a pointer is a form of chain of pointers. Normally, a pointer contains the address of a variable. When we define a pointer to a pointer, the first pointer contains the address of the second pointer, which points to the location that contains the actual value as shown below.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With