I'd like to do something like the following:
type Model interface {
EntityType() string
GetKey() *datastore.Key
SetKey(*datastore.Key) error
PreSave(context.Context) error
PostSave(context.Context) error
PostLoad(context.Context) error
}
type Models []Model interface {
Prepare(int) ([]Model, error)
}
So that the struct Models
is also an interface and would get implemented by a slice of the structs that implement Model
. Something like the following:
type Foo struct {
key *datastore.Key `datastore:"_"`
// ... other things here
}
// assume all Model interface funcs are here and valid
type Foos []Foo
func (f *Foos) Prepare (num int) ([]Model, error) {
// do the preparations for Foo slice
}
Obviously, the code above throws errors and isn't possible. But is there some code that would produce basically the same functionality? Without using reflect
or anything costly like that?
Obviously a simple
type Models interface {
Prepare(int) ([]Model, error)
}
type Foos []Foo
func (f Foos) Prepare(num int) ([]Model, error) {
// do the preparations for Foo slice
return nil, nil
}
func main() {
foos := Foos{}
models := Models(foos)
models.Prepare(17)
}
works.
So what is your actual question? Please see also https://golang.org/doc/faq#covariant_types and https://golang.org/doc/faq#convert_slice_of_interface Which should make it a bit clearer.
I would recommend to provide function (! not methods) to operate on []Model
and not to abstract the slice-of-model into some higher type.