How to get embedded type from GO struct? -


i trying embedded type go structs. below example program demonstrates this. there way write myfunc() without enumerating every type can come in input? https://play.golang.org/p/5wp14o660m

package main  import (     "fmt" )  type objectmeta struct {     name string     namespace string }  type struct {     objectmeta     x string }  type b struct {     objectmeta      x string }  func myfunc(v interface{}) objectmeta {     switch u := v.(type) {     case *a:         return u.objectmeta     case a:         return u.objectmeta     case *b:         return u.objectmeta     case b:         return u.objectmeta     }     panic("no matching type") }  func main() {     fmt.println(myfunc(&a{}))      var v interface{} = &a{}     fmt.println(v.(*objectmeta)) } 

objectmeta, a, b structs exist in external project. have no control on them.

it can done using reflection, iterating through fields of incoming value:

func myfunc(v interface{}) objectmeta {     // elem() de-reference pointer     ifv := reflect.valueof(v).elem()     ift := reflect.typeof(v).elem()      := 0; < ift.numfield(); i++ {         f := ift.field(i)         if f.name == "objectmeta" {             fv := ifv.field(i)             return fv.interface().(objectmeta)         }     }     panic("objectmeta not found") } 

playground: https://play.golang.org/p/czmhjwhxyr


Comments

Popular posts from this blog

ios - MKAnnotationView layer is not of expected type: MKLayer -

ZeroMQ on Windows, with Qt Creator -

unity3d - Unity SceneManager.LoadScene quits application -