Golang:在LRU缓存中存储地图结构的正确方法

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:

  • whatever you decide, make sure access to this LRU is thread-safe if you plan to use it within goroutines.
  • you may store *map instead of plain map, which would eliminate a need to call add.
  • if it's ok to add to the map with override, skip presence check (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.