首页 > 解决方案 > 从接口获取底层 reflect.Value{}

问题描述

我正在尝试编写一个函数,通过使用 reflect.Type 提供底层类型,在空接口 {} 中返回底层 reflect.Value:

// 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!")
    }
}

如代码中所写,类型断言不起作用,因为“reflect.Type”不是类型。

有谁知道如何解决它?最好不要进入接口的底层结构中的 uintptr (如果有这样的方法)。

谢谢!

标签: goreflection

解决方案


Go 是一种静态类型的语言,您不能将断言键入“动态类型”。

但你不必这样做。“包装”值中可用的任何具体值interface{}不需要魔法,只需将其按原样传递给reflect.ValueOf()

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

或者简单地说:

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

(这个功能甚至没有理由存在了,它是如此简单..)

在Go Playground上尝试一下。

interface{}当你做的下一个也是唯一的操作是将它传递给一个期望的函数时,没有必要从一个具体类型断言interface{}。它将再次被包裹在一个interface{}.


推荐阅读