如何创建一个通用函数来解组所有类型? [英] How to create a generic function to unmarshal all types?

查看:44
本文介绍了如何创建一个通用函数来解组所有类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在下面有一个函数,我想使其泛型:

I have a function below, and I would like to make it generic:

func genericUnmarshalForType1(file string) Type1 {

  raw, err := ioutil.ReadFile(file)

  if err != nil {
      fmt.Println(err.Error())
      os.Exit(1)
  }

  var type1 Type1

  json.Unmarshal(raw, &type1)
}

我想创建一个接受Type1或Type2的函数,而无需为每个类型创建一个函数.我该怎么办?

I would like to create a function that accepts Type1 or Type2 without the need to create a function per type. How can I do this?

推荐答案

以与 json.Unmarshal 相同的方式进行操作:

Do it the same way json.Unmarshal does it:

func genericUnmarshal(file string, v interface{}) {
    // File emulation.
    raw := []byte(`{"a":42,"b":"foo"}`)
    json.Unmarshal(raw, v)
}

游乐场: http://play.golang.org/p/iO-cbK50BE.

通过实际返回遇到的任何错误,可以使此功能更好.

You can make this function better by actually returning any errors encountered.

这篇关于如何创建一个通用函数来解组所有类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆