I'm writing a function that retrieves arbitrary data from a database, and returns a slice of structs with the results. The data structure is defined by the user in an ItemFactory. The user then implements methods on the factory, that create empty structs:
func (t Example) GenerateEmptyItem() interface{} {
return &Example{}
}
I am trying to do the same for slices of Example
. I need to be able to use whatever is returned, to call functions such as len()
, while at the same time, keeping it generic as to allow it to be returned by "generic" functions.
I can't simply have something like this, as the underlying data allocation for a slice of interfaces is different from a slice of Examples:
func (t Country) GenerateEmptyItems() []interface{} {
return []Country{} //Error
}
Is it possible to use a pointer to a slice, such as &[]Example{}
and pass it as an interface{}
, and then still be able to use it as a slice? Or am I going about this wrong?.Remember, I don't know the type of the data at compile-time, so I can't simply cast.
I appreciate any help. Let me know if I can clarify anything.