golang: convert struct pointer to interface{} -


if have:

   type foo struct{    }     func bar(baz interface{}) {    } 

the above set in stone - can't change foo or bar. additionally, baz must converted foo struct pointer inside bar. how cast &foo{} interface{} can use parameter when calling bar?

to turn *foo interface{} trivial:

f := &foo{} bar(f) // every type implements interface{}. nothing special required 

in order *foo, can either type assertion:

func bar(baz interface{}) {     f, ok := baz.(*foo)     if !ok {         // baz not of type *foo. assertion failed     }      // f of type *foo } 

or type switch (similar, useful if baz can multiple types):

func bar(baz interface{}) {     switch f := baz.(type) {     case *foo: // f of type *foo     default: // f other type     } } 

Comments

Popular posts from this blog

google api - Incomplete response from Gmail API threads.list -

Installing Android SQLite Asset Helper -

Qt Creator - Searching files with Locator including folder -