diff --git a/cache.go b/cache.go index 93943da..a1547fc 100644 --- a/cache.go +++ b/cache.go @@ -478,6 +478,13 @@ func (c *Cache[K, V]) Items() map[K]*Item[K, V] { // Range stops the iteration. func (c *Cache[K, V]) Range(fn func(item *Item[K, V]) bool) { c.items.mu.RLock() + + // Check if cache is empty + if c.items.lru.Len() == 0 { + c.items.mu.RUnlock() + return + } + for item := c.items.lru.Front(); item != c.items.lru.Back().Next(); item = item.Next() { i := item.Value.(*Item[K, V]) c.items.mu.RUnlock() diff --git a/cache_test.go b/cache_test.go index a7d5d1a..07bf8c5 100644 --- a/cache_test.go +++ b/cache_test.go @@ -806,6 +806,13 @@ func Test_Cache_Range(t *testing.T) { }) assert.Equal(t, []string{"5", "4"}, results) + + emptyCache := New[string, string]() + assert.NotPanics(t, func() { + emptyCache.Range(func(item *Item[string, string]) bool { + return false + }) + }) } func Test_Cache_Metrics(t *testing.T) {