登录
首页 >  Golang >  Go问答

动态返回类型的函数

来源:stackoverflow

时间:2024-03-15 08:12:25 113浏览 收藏

本篇文章向大家介绍《动态返回类型的函数》,主要包括,具有一定的参考价值,需要的朋友可以参考一下。

问题内容

我有一个从其他包调用的函数。该函数解析参数中接收到的文本字符串并返回结构体的拼接。在我的例子中,这些结构有 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 仅存在于 switch case 的范围内,它并不能真正解决我的问题。

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 以返回 [] 接口{}

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 中使用 [] 接口{}

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

好了,本文到此结束,带大家了解了《动态返回类型的函数》,希望本文对你有所帮助!关注golang学习网公众号,给大家分享更多Golang知识!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>