Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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
like image 622
Elad Avatar asked Apr 27 '16 13:04

Elad


People also ask

How do I get pointer value in Go?

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.

What is the type of a pointer in Go?

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.

Does Go support pointer?

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.

Can you define a pointer to pointer in Go?

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.


1 Answers

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

like image 67
icza Avatar answered Oct 13 '22 00:10

icza