我正在尝试编写一个函数,通过使用 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/