Search code examples
gointerfaceunmarshalling

How to create a generic function to unmarshal all types?


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?


Solution

  • 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.