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)
}
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?
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)
}
Playground: http://play.golang.org/p/iO-cbK50BE.
You can make this function better by actually returning any errors encountered.
Go doesn't support generics, but you can write something like this:
func genericUnmarshalForType1(file string) interface{} {
raw, err := ioutil.ReadFile(file)
if err != nil {
fmt.Println(err.Error())
os.Exit(1)
}
var x interface{}
if err = json.NewDecoder(raw).Decode(x); err != nil {
return nil
}
return x
}
func main() {
x := genericUnmarshalForType1("filename.json");
var t1 Type1
var t2 Type2
switch t := x.(type) {
case Type1:
t1 = t
case Type2:
t2 = t
}
}
Also I recommend you to read http://attilaolah.eu/2013/11/29/json-decoding-in-go/ about Unmarshal
using and data types.