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?
CodePudding user response:
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.
