Home > database >  Is it possible to extract the value of an interface from a pointer to the interface using reflection
Is it possible to extract the value of an interface from a pointer to the interface using reflection

Time:06-01

What I could come up with so far doesn't seem to work:

package main

import (
    "fmt"
    "reflect"
)

type someStruct struct {
    id string
}

func main() {
    var struRef interface{} = someStruct{"Some ID"}
    var iref = &struRef

    fmt.Printf("Hello, % v!\n", reflect.ValueOf(iref).Elem().String())
    fmt.Printf("Hello, % v!\n", reflect.ValueOf(reflect.ValueOf(iref).Elem()).String())
}

To clarify: I would like to access the id field of someStruct having access only to the iref variable.

CodePudding user response:

You are dealing with a pointer to an interface, thus:

fmt.Printf("Hello, % v!\n", reflect.ValueOf(iref).Elem().Elem().FieldByName("id").String())

should work. The first Elem dereferences the pointer to the interface. The second Elem accesses the struct contained in the interface.

  •  Tags:  
  • go
  • Related