Elegant go cache using type composition

This is a neat little trick I recently learned. You can compose any object, e.g. a map[string]string (but really anything else) with a sync.Mutex into a single object. This composition makes generating cache objects in a very elegant way. Checkout this example:

var cache = struct {
	sync.Mutex
	values map[string]string
}{
	values: make(map[string]string, 0),
}

cache.Lock()
defer cache.Unlock()
cache.values["1"] = "one"
cache.values["2"] = "two"

Here you can use the cache object just like a map[string]string but it also has the methods from sync.Mutex, so you also can use it’s .Lock() and .Unlock() values directly. And the mutex is encapsuled together with the object it should guard.

Neat!

Licensed under CC BY-NC-SA 4.0