[英]Go obtain pointer to struct from interface?
Given an interface, how do I obtain a pointer to the underlying value? 给定一个接口,我如何获得指向基础值的指针?
My naive attempt was to use a type assertion like this: 我天真的尝试是使用这样的类型断言:
var mytypeptr *MyType = myinterface.(*MyType)
But I get: 但是我得到:
interface conversion: MyInterface is MyType, not *MyType
You could start with, using reflect.Indirect()
: 您可以使用
reflect.Indirect()
:
val := reflect.ValueOf(myinterface)
if val.Kind() == reflect.Ptr {
val = reflect.Indirect(val)
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.