函数解组到结构体的正确模式是什么?

huangapple go评论144阅读模式
英文:

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

将占位符a1a2T1T2替换为适合您函数的参数。

在 playground 上运行示例

英文:

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.

Run an example on the playground.

huangapple
  • 本文由 发表于 2021年11月5日 06:04:20
  • 转载请务必保留本文链接:https://go.coder-hub.com/69846347.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定