从接口获取基本的反射。价值{}

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!

Go is a statically typed language, you can't type assert to "dynamic types".

But you don't have to. "Wrapping" any concrete value available in an interface{} value requires no magic, just pass that as-is to reflect.ValueOf():

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

Or simply:

func getUnderlyingAsValue(data interface{}) reflect.Value {
    return reflect.ValueOf(data)
}

(This function isn't even justified to exist anymore, it's so simple..)

Try it on the Go Playground.

There is no point type-asserting a concrete type from an interface{} when the next and only operation you do is pass it to a function that expects interface{}. It would again be wrapped in an interface{}.