英文:
Correct pattern to use for a function unmarshaling into a struct?
问题
我有一个名为callAPI的函数,返回类型是interface{}。
我有一个结构体Company,我想要从callAPI()返回的JSON中进行Unmarshal()操作。
我应该让callAPI()返回一个Company{}吗?
还是应该让callAPI()返回[]byte,然后再将其Unmarshal()为一个Company?
或者,是否有其他方法可以实现我想要的效果?
英文:
I have a function, callAPI, with a return-type interface{}.
I have a struct, Company, in which I want to Unmarshal() the resulting JSON from callAPI().
Should I instead have callAPI() return a Company{}?
Or, should I have callAPI() return []byte, and then Unmarshal() into a Company?
Or, is there another way to accomplish what I'm trying to achieve?
答案1
得分: 2
将指向目标值的指针作为参数传递。将指针值传递给json.Unmarshal:
func callAPI(a1 T1, a2 T2, v interface{}) error {
// 使用a1、a2等获取API响应[]byte,p
return json.Unmarshal(p, v)
}
像这样调用它:
var c Company
err := callAPI(a1, a2, &c)
if err != nil {
// 处理错误
}
// 使用company
将占位符a1、a2、T1和T2替换为适合您函数的参数。
英文:
Pass a pointer to the target value as an argument. Pass the pointer value through to json.Unmarshal:
func callAPI(a1 T1, a2 T2, v interface{}) error {
// use a1, a2, ... to get API response []byte, p
return json.Unmarshal(p, v)
}
Call it like this:
var c Company
err := callAPI(a1, a2, &c)
if err != nil {
// handle error
}
// Use company.
Replace the placeholders a1, a2, T1 and T2 with whatever arguments are appropriate for your function.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论