samedi 30 septembre 2017

Golang function that filling interfaces array without reflect

I want to create an abstract function, that gets data from DB and fills array by this data. Types of array can be different. And I want to do it without reflect, due to performance issues. I just want to call everywhere some function like GetDBItems() and get array of data from DB with desired type. But all implementations that I create are owful.

Here is this function implementation:

type AbstractArrayGetter func(size int) []interface{}

func GetItems(arrayGetter AbstractArrayGetter) {
    res := DBResponse{}
    DB.Get(&res)
    arr := arrayGetter(len(res.Rows))
    for i := 0; i < len(res.Rows); i++ {
        json.Unmarshal(res.Rows[i].Value, &obj[i])
    }
}

Here I call this function:

var events []Event
GetFullItems("events", "events_list", map[string]interface{}{}, func(size int) []interface{} {
        events = make([]Event, size, size)
        proxyEnt := make([]interface{}, size, size)
        for i, _ := range events {
            proxyEnt[i] = &events[i]
        }
        return proxyEnt
    })

It works, but there are to much code to call this function, also there is some perfomance issue about copying events array to interfaces array.

How can I do it without reflect and do it with a short function call code? Or reflect not to slow in this case?





Aucun commentaire:

Enregistrer un commentaire