函数的动态返回类型



我有一个从其他包调用的函数。这个函数解析在参数中接收到的文本字符串,并返回一个结构体拼接。在我的例子中,这些结构有7个,它们在某些领域有所不同。我试图返回一个interface{}类型,但我希望能够断言接收端的类型,因为我需要对该结构体进行其他操作。

到目前为止,我已经到了这一点(函数应该在不同的包中):

func Process(input string) interface{} {
// ...
switch model {
case 1:
output := model1.Parse(input) // this function returns a []MOD1 type
return output
}
case 2:
output := model2.Parse(input) // this function returns a []MOD2 type
return output
}
// other cases with other models
}
func main() {
// ...
output := package.Process(input) // now output is of type interface{}

// I need the splice because I'll publish each element to a PubSub topic
for _, doc := range output {
obj, err := json.Marshal(doc)
if err != nil {
// err handling
}
err = publisher.Push(obj)
if err != nil {
// err handling
}
}
}

现在在main()中,我希望output的类型为[]MOD1,[]MOD2,…,或[]MOD7.

我已经尝试过使用switch t := output.(type),但t只存在于开关情况的范围内,它并不能真正解决我的问题。

func main() {
output := package.Process(input)
switch t := output.(type) {
case []MOD1:
output = t // output is still of type interface{}
case []MOD2:
output = t
}
}

我需要这个,因为在main函数中,我必须对该结构进行其他操作,并最终将其马歇尔为JSON。我想过在Process函数中编组结构并返回[]byte,但随后我需要在不知道结构体类型的情况下在main中解组。

更改Process1以返回[]interface{}:

func Process(input string) []interface{} {
// ...
switch model {
case 1:
output := model1.Parse(input)
result := make([]interface{}, len(output))
for i := range result {
result[i] = output[i]
}
return result
}
case 2:
// other cases with other models
}

使用main:

中的[]interface{}
output := package.Process(input)
for _, doc := range output {
obj, err := json.Marshal(doc)
if err != nil {
// err handling
}
err = publisher.Push(obj)
if err != nil {
// err handling
}
}

最新更新