Go obtain pointer to struct from interface?

huangapple go评论88阅读模式
英文:

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)
}

huangapple
  • 本文由 发表于 2014年9月20日 01:02:57
  • 转载请务必保留本文链接:https://go.coder-hub.com/25938989.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定