Search code examples
jsongostructgeneralization

Generalization in structs - golang


I have this function to read a JSON file into a Driver struct:

func getDrivers() []Driver {
    raw, err := ioutil.ReadFile("/home/ubuntu/drivers.json")
    if err != nil {
        fmt.Println(err.Error())
        os.Exit(1)
    }

    var d []Driver
    json.Unmarshal(raw, &d)
    return d
}

How can I change this function to also work with a Pilot struct? I tried using []interface{} without success.

Thank you


Solution

  • Change the signature of your function to make it generic, and pass the slice as argument. The following should work:

    func getDriversOrPilots(file string, slice interface{}) {
        raw, err := ioutil.ReadFile(file)
        if err != nil {
            fmt.Println(err.Error())
            os.Exit(1)
        }
    
        json.Unmarshal(raw, slice)
    }
    
    func getDrivers() []Driver {
        var d []Driver
        getDriversOrPilots("/home/ubuntu/drivers.json", &d)
        return d
    }
    
    func getPilots() []Pilot {
        var p []Pilot
        getDriversOrPilots("/home/ubuntu/pilots.json", &p)
        return p
    }