简体   繁体   中英

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() :

val := reflect.ValueOf(myinterface)
if val.Kind() == reflect.Ptr {
    val = reflect.Indirect(val)
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM