go - golang: slice of struct != slice of interface it implements? -
i have interface model
, implemented struct person
.
to model instance, have following helper functions:
func newmodel(c string) model { switch c { case "person": return newperson() } return nil } func newperson() *person { return &person{} }
the above approach allows me return typed person instance (can add new models later same approach).
when attempted similar returning slice of models, error. code:
func newmodels(c string) []model { switch c { case "person": return newpersons() } return nil } func newpersons() *[]person { var models []person return &models }
go complains with: cannot use newpersons() (type []person) type []model in return argument
my goal return slice of whatever model type requested (whether []person
, []futuremodel
, []terminator2000
, w/e). missing, , how can implement such solution?
this similar question answered: https://stackoverflow.com/a/12990540/727643
the short answer correct. slice of structs not equal slice of interface struct implements.
a []person
, []model
have different memory layouts. because types slices of have different memory layouts. model
interface value means in memory 2 words in size. 1 word type information, other data. person
struct size depends on fields contains. in order convert []person
[]model
, need loop on array , type conversion each element.
since conversion o(n) operation , result in new slice being created, go refuses implicitly. can explicitly following code.
models := make([]model, len(persons)) i, v := range persons { models[i] = model(v) } return models
and dskinner pointed out, want slice of pointers , not pointer slice. pointer slice not needed.
*[]person // pointer slice []*person // slice of pointers
Comments
Post a Comment