Skip to content

Commit 40763d5

Browse files
Jeremy BowersCode-Hex
Jeremy Bowers
authored andcommitted
Add a GetDefault method.
1 parent 5303a9a commit 40763d5

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
@@ -222,6 +222,22 @@ func (c *Cache[K, V]) Get(key K) (zero V, ok bool) {
222222
return item.Value, true
223223
}
224224

225+
// GetDefault atomically gets a key's value from the cache, or if the
226+
// key is not present, sets the given value.
227+
func (c *Cache[K, V]) GetDefault(key K, val V, opts ...ItemOption) V {
228+
c.mu.Lock()
229+
defer c.mu.Unlock()
230+
item, ok := c.cache.Get(key)
231+
232+
if !ok || item.Expired() {
233+
item := newItem(key, val, opts...)
234+
c.cache.Set(key, item)
235+
return val
236+
}
237+
238+
return item.Value
239+
}
240+
225241
// DeleteExpired all expired items from the cache.
226242
func (c *Cache[K, V]) DeleteExpired() {
227243
c.mu.Lock()

0 commit comments

Comments
 (0)