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
Post a Comment