将任意struct作为函数参数传递

时间:2017-11-01 14:31:04

标签: go

我正在处理二进制文件。我需要一个函数,它采用任意结构并返回这些结构的数组。我该怎么做?以下是我尝试完成的一个简单示例。目前,我为每个结构都有一个功能。唯一的区别在于:

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)
   ...
}

1 个答案:

答案 0 :(得分:0)

您可能希望返回切片而不是数组。

您可以使用reflect.MakeSlice()函数进行切片,并获取可以使用reflect.TypeOf()函数的任意对象的类型

我在https://github.com/strongo/app/blob/master/db/interfaces.go& https://github.com/strongo/app/blob/master/gaedb/database.go

中使用的https://github.com/strongo/bots-framework
相关问题