Search code examples
pointersgodereference

How to deref a pointer dynamically in Golang


I have this func:

func getStringRepresentation(v interface{}, size int, brk bool, depth int) string {

    val := reflect.ValueOf(v)

    if val.Kind() == reflect.Ptr {
        v = *v.(types.Pointer)   // does not work
        val = reflect.ValueOf(v)
    }

   // ...

}

how can I dereference the pointer to get the value of it? When I use:

v = *v.(types.Pointer)

The error says:

Invalid indirect of 'v.(types.Pointer)' (type 'types.Pointer')

I tried this:

val := reflect.ValueOf(v)

if val.Kind() == reflect.Ptr {
    v = v.(types.Pointer).Underlying()
    val = reflect.ValueOf(v)
}

and I tried this too:

val := reflect.ValueOf(v)

if val.Kind() == reflect.Ptr {
    v = val.Elem()
    val = reflect.ValueOf(v)
}

I need to get the value of the interface{} from the pointer.


Solution

  • You can dereference pointers using reflect using Elem:

    val := reflect.ValueOf(v)
    if val.Kind() == reflect.Ptr {
       val = val.Elem()
    }
    

    After the if statement, val is a reflect.Value representing the value passed in by the interface. If the value passed in is a pointer, val now has the dereferenced value of that pointer.