dongyuan3094 2014-09-19 17:02
浏览 25
已采纳

从接口去获取指向结构体的指针?

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条回答 默认 最新

  • dpecb06062 2014-09-19 17:07
    关注

    You could start with, using reflect.Indirect():

    val := reflect.ValueOf(myinterface)
    if val.Kind() == reflect.Ptr {
        val = reflect.Indirect(val)
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?