go - 从 interface{} 获取底层 reflect.Value

标签 go reflection

我正在尝试编写一个函数,通过使用 reflect.Type 提供底层类型,在空接口(interface){}中返回底层 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”不是类型。

有人知道怎么解决吗?最好不要在接口(interface)的底层结构中进入 uintptr(如果有这样的方法)。

谢谢!

最佳答案

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){}中。

关于go - 从 interface{} 获取底层 reflect.Value,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56474332/

相关文章:

c# - 如何使用 FastMember 设置嵌套属性值

go - Iota 在 Go map 上定义键?

HTTP 服务不工作

不能用宏包装 cgo 标志

sockets - 多个 http.Requests 给出 "can' t 分配请求的地址,“除非加速

.net - 为什么 PropertyInfo SetValue 和 GetValue 这么慢?

java - 为什么Java Singleton需要防止反射攻击

go - 为什么golang yaml头部注释解码后变成脚注释

.net - 反射,有IsClass但没有IsStruct?

c# - 询问 MethodInfo 它需要多少参数的最有效方法是什么?