I have a structure like: map[key]value
, and I want to store it in "github.com/golang/groupcache/lru"
by a string key, say, the cacheKey
.
Here is my question:
I found whenever I want update the cached item, I need to Get
it first:
item := cache.Get(cacheKey)
if v, ok := item[key]; ok{
item[key]=new_value
cache.Add(cacheKey, item)
}
Is it right way to do this?
Or, as some of people suggested, I need to re-design my structure to make sure I can do cache.Add(cacheKey, item)
whenever I want to update it.
Or, I should even use a combined key like cacheKey_key
to store that item?
The code above will work. I looked at the source of LRU cache you refer to. Here are my notes:
*map
instead of plain map
, which would eliminate a need to call add.if v, ok...
)So having said that, here is what it becomes:
m sync.Mutex
m.Lock()
defer m.Unlock()
cache.Get(cacheKey)[key] = new_value
If you elaborate on what sort of data you are planning to store, we may try to come up with an alternative solution.