英文:
Go obtain pointer to struct from interface?
问题
给定一个接口,我如何获得指向底层值的指针?
我尝试使用类型断言来实现,像这样:
var mytypeptr *MyType = myinterface.(*MyType)
但是我得到了以下错误:
interface conversion: MyInterface is MyType, not *MyType
英文:
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
答案1
得分: 0
你可以使用reflect.Indirect()
来开始:
val := reflect.ValueOf(myinterface)
if val.Kind() == reflect.Ptr {
val = reflect.Indirect(val)
}
英文:
You could start with, using reflect.Indirect()
:
val := reflect.ValueOf(myinterface)
if val.Kind() == reflect.Ptr {
val = reflect.Indirect(val)
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论