Vip*_*old 1 interface go unmarshalling
我有一个下面的函数,我想使其通用:
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)
}
Run Code Online (Sandbox Code Playgroud)
我想创建一个接受 Type1 或 Type2 的函数,而不需要为每种类型创建一个函数。我怎样才能做到这一点?
按照同样的方式做json.Unmarshal
:
func genericUnmarshal(file string, v interface{}) {
// File emulation.
raw := []byte(`{"a":42,"b":"foo"}`)
json.Unmarshal(raw, v)
}
Run Code Online (Sandbox Code Playgroud)
游乐场:http://play.golang.org/p/iO-cbK50BE。
您可以通过实际返回遇到的任何错误来改进此函数。
归档时间: |
|
查看次数: |
1653 次 |
最近记录: |