![]()
Collectionをキーから、値やオブジェクトをMapにキャッシュする処理を私がよく使うのでキャッシュ用の関数作りました。
もくじ
Function
package cache
// GetCacheMapByFunc extracts keys and values from targets to create a cache.
func GetCacheMapByFunc[T any, K comparable, V any](targets []T, extractKey func(T) (K), extractValue func(T) (V)) (map[K]V) {
cache := make(map[K]V, len(targets))
for _, target := range targets {
key := extractKey(target)
value := extractValue(target)
cache[key] = value
}
return cache
}
Client
type UserIDsCacheMap map[string]value.ID
func getUserIDsCacheMap(users []*model.User) (UserIDsCacheMap) {
getKeyFunc := func(u *model.User) (string) {
return u.key
}
getValueFunc := func(u *model.User) (value.ID) {
return u.ID
}
userIDsCacheMap := cache.GetCacheMapByFunc(users, getKeyFunc, getValueFunc)
return userIDsCacheMap
}
PHP版だとこれ




