go - 从接口获取底层 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 (如果有这样的方法)。
谢谢!
解决方案
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{}
.
推荐阅读
- google-apps-script - 仅在 1 张纸上运行功能,而不是 .forEach
- javascript - nuxt , vuex 不返回已登录的用户信息
- flutter - LinearGradient:Container右侧一像素垂直线
- javascript - 显示给定位置的文件夹数量
- c++ - C++ 结构/类成员
- python - 将 Django REST 框架与 TCP 服务器套接字一起使用
- php - 无法打印到此打印机:无法将文件复制到打印机。使用 mike42 时显示错误
- javascript - 传入一个新数组并显示一条消息 - 骰子首先完成
- python - 递归函数返回值而不分配额外空间?
- python - 是否可以更改此代码以删除其循环并替换为 tensorflow?