Passing array of structs to a function in Go -
i have object parsed xml file. has struct type this
type report struct { items []item `xml:......` anotheritems []anotheritem `xml:......` } type item struct { name string } type anotheritem struct { name string } func (item *item) foo() bool { //some code here } func (anotheritem *anotheritem) foo() bool { //another code here }
for each item have smth this:
func main(){ //some funcs called report object dosmth(report.items) dosmth(report.anotheritems) } func dosmth(items ????){ _, item : range items { item.foo() } }
since have different items same function want have 1 dosmth
can't dosmth(items []item)
, question - should write instead of "????" working? way made pass report.items dosmth()
func dosmth(items interface{})
but throws me error "cannot range on items (type interface {})" , if instead of iteration put smth
func dosmth(items interface{}){ fmt.println(items) }
program print list of items
replace ????
[]item
: go playground. same how variable report.items
defined in struct report
.
ok, yes change question. thing thought of needed create interface such itemer
, have []itemer
in function definition of dosmth
:
type itemer interface { foo() bool } func dosmth(items []itemer) { ... }
unfortunately this not seem possible. tried other permutations including using interface{}
, []interface{}
variadic functions , couldn't work.
after doing research turns out go not convert type of slices. if each element of slice instance of interface such itemer
or interface{}
still won't it. i not re-find source apparently due fact new slice have created , each element have type cast individually old slice new slice: https://stackoverflow.com/a/7975763/2325784.
to me suggests function such dosmth
not possible.
the thing suggest restructure code. if willing post more information foo
, dosmth
can try that.
Comments
Post a Comment