jeudi 6 juin 2019

Get underlying reflect.Value from interface{}

I'm trying to write a function that returns the underlying reflect.Value within empty interface{} by providing the underlying type using reflect.Type:

// code in: https://play.golang.org/p/p6NLm18LjzM
package main

import (
    "fmt"
    "reflect"
)

type MyInt struct{
    x int
}

func getUnderlyingAsValue( data interface{}, underlyingType reflect.Type) reflect.Value{

    underlyingData := data.(underlyingType) // <-- Doesn't compile "underlyingType is not a type"
    return reflect.ValueOf(underlyingData)

}

func main() {

    var i int
    i = 5
    myInt := &MyInt{x:i}

    underVal := getUnderlyingAsValue(myInt, reflect.TypeOf(i))

    if underVal.Type() != reflect.TypeOf(myInt){
        fmt.Printf("Doesn't Work! :-(")
    } else {
        fmt.Printf("SUCCESS!")
    }
}

As written within the code, type assertion doesn't work because "reflect.Type" is not a type.

Does anyone have any idea how to solve it? Preferably without going into uintptr in the underlying structure of an interface (if there is such a way).

Thanks!





Aucun commentaire:

Enregistrer un commentaire