It is not easy to lock only one entry, but you wanna more efficient, a good practice in Go is to use channel to communicate with a sequential process. In this way, there is no shared variables and locks.
a simple example of this:
type request struct {
reqtype string
key string
val interface{}
response chan<- result
}
type result struct {
value interface{}
err error
}
type Cache struct{ requests chan request }
func New() *Cache {
cache := &Cache{requests: make(chan request)}
go cache.server()
return cache
}
func (c *Cache) Get(key string) (interface{}, error) {
response := make(chan result)
c.requests <- request{key, response}
res := <-response
return res.value, res.err
}
func (c *Cache) Set(key, val string) {
c.requests <- request{"SET", key, val, response}
}
func (c *Cache) server() {
cache := make(map[string]interface{})
for req := range memo.requests {
switch req.reqtype {
case "SET":
cache[req.key] = req.val
case "GET":
e := cache[req.key]
if e == nil {
req.response <- result{e, errors.New("not exist")}
} else {
req.response <- result{e, nil}
}
}
}
}