Skip to content

Commit 2b64d74

Browse files
author
Jeremy Bowers
committed
Add a GetDefault method.
1 parent 9f98378 commit 2b64d74

File tree

1 file changed

+16
-0
lines changed

1 file changed

+16
-0
lines changed

cache.go

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -214,6 +214,22 @@ func (c *Cache[K, V]) Get(key K) (value V, ok bool) {
214214
return item.Value, true
215215
}
216216

217+
// GetDefault atomically gets a key's value from the cache, or if the
218+
// key is not present, sets the given value.
219+
func (c *Cache[K, V]) GetDefault(key K, val V, opts ...ItemOption) V {
220+
c.mu.Lock()
221+
defer c.mu.Unlock()
222+
item, ok := c.cache.Get(key)
223+
224+
if !ok || item.Expired() {
225+
item := newItem(key, val, opts...)
226+
c.cache.Set(key, item)
227+
return val
228+
}
229+
230+
return item.Value
231+
}
232+
217233
// DeleteExpired all expired items from the cache.
218234
func (c *Cache[K, V]) DeleteExpired() {
219235
c.mu.Lock()

0 commit comments

Comments
 (0)