英文:
Generalization in structs - golang
问题
我有这个函数来将一个JSON文件读入一个Driver结构体:
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
}
我该如何修改这个函数,使其也适用于Pilot结构体?
我尝试使用[]interface{}但没有成功。
谢谢。
英文:
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
答案1
得分: 1
将函数的签名更改为通用的,并将切片作为参数传递。以下是修改后的代码:
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
}
请注意,这里使用了空接口类型 interface{} 来接收切片参数,以实现通用性。
英文:
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
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论