Rather than having multiple API fetching functions, I want to make one function that can fetch the appropriate database, format it into a slice of structs, and return it. Below is a simplified version of my code:
type Person struct {
Name string `json:"name"`
IsCool bool `json:"is_cool"`
}
type Pet struct {
Name string `json:"name"`
IsFluffy bool `json:"is_fluffy"`
}
type Group struct {
Name string `json:"name"`
CreationDate time.Time `json:"creation_date"`
}
type generic interface{}
func FetchDB(dbName string) interface {
var collection []generic
var model generic
switch dbName {
case "users":
collection = new([]User)
model = new(User)
}
case "pets":
collection = new([]Pet)
model = new(Pet)
case "groups":
collection = new([]Group)
model = new(Group)
default:
return nil
}
iter := client.DB(dbName).Get()
for {
entry, err := iter.Next()
if err != nil {
break
}
entry.ToStruct(&model)
collection = append(collection, model)
}
return collection
}
However, calling this function results in cannot use new([]User) (type *[]User) as type []generic in assignment
. My first question is how I can create a "generic" slice, and assign a type to it. My second question is whether this is a correct way to set up this function—using the generic
interface feels hacky!—and if it is not, what would be a more sensible way to then design this function.
sqlx.Get
,json.Unmarshal
, etc. do. – Adrian