#Best approach to handle function and struct abstraction

3 messages · Page 1 of 1 (latest)

delicate fossil
#

What would be the best approach to create a modular function that abstracts structs that represent different API calls instead of creating 7 different methods that do exactly the sme thing like I do here ?

func (s *ServiceJob) findNewCityData(apiData []structs.City, tableData map[int]struct{}) []structs.City {
    var newData []structs.City

    for _, a := range apiData {
        if _, exists := tableData[a.CityID]; !exists {
            newData = append(newData, a)
        }
    }

    return newData
}

func (s *ServiceJob) findNewCountryData(apiData []structs.Country, tableData map[int]struct{}) []structs.Country {
    var newData []structs.Country

    for _, a := range apiData {
        if _, exists := tableData[a.CountryIsoNumeric]; !exists {
            newData = append(newData, a)
        }
    }

    return newData
}

Generic fucntion ?

stiff plover
#

idk what best looks like, but I see at least two options
1 - go func filterthingie[T any, K comparable](apiData []T, tableData map[K]struct{}, keyfunc func(T) K) []T
2 - ```go
func filterthingie[T Thingie[K], K comparable](apiData []T, tableData map[K]struct{}) []T

type Thingie[T comparable] interface { ID() T }```

option 1 is more flexible, option 2 is more ergonomic (i's interfaces without the required boxing)

delicate fossil
#

Thank you very much, im not home but i'll provid efeedback tonight or tomorrow.