I'm processing binary files. I need a function which takes an arbitrary structure and returns an array of those structures. How would I do this? Below is a simple example of what I'm trying to accomplish. Currently, I have a function for each of the structures. The only difference is in the line:
dataBuf, err := make([]arbitrary_struct_type, numRecs)
type structA struct {
id int32
sDate float64
name string
}
type structB struct {
area int32
polygon string
}
type structC struct {
sTime float64
eTime float64
tSlice int32
kml string
}
func readDataset(grp *Group, arbitrary_struct_type type) ([]arbitrary_struct_type type, error) {
...
dataBuf, err := make([]arbitrary_struct_type, numRecs)
...
return dataBuf, err
}
func main() {
...
a, err := readDataset(grp1, structA)
...
b, err := readDataset(grp2, structB)
...
c, err := readDataset(grp3, structC)
...
}
You probably want to return a slice and not an array.
You can use reflect.MakeSlice()
function to make slice, and to get type of the arbitrary object you can use reflect.TypeOf()
function
I'm doing something similar in https://github.com/strongo/app/blob/master/db/interfaces.go & https://github.com/strongo/app/blob/master/gaedb/database.go which are used in https://github.com/strongo/bots-framework