Skip to content

Commit ad21351

Browse files
committed
fixed GetDefault to be GetOrSet
1 parent 40763d5 commit ad21351

File tree

2 files changed

+19
-4
lines changed

2 files changed

+19
-4
lines changed

cache.go

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -222,20 +222,21 @@ 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
225+
// GetOrSet atomically gets a key's value from the cache, or if the
226226
// key is not present, sets the given value.
227-
func (c *Cache[K, V]) GetDefault(key K, val V, opts ...ItemOption) V {
227+
// The loaded result is true if the value was loaded, false if stored.
228+
func (c *Cache[K, V]) GetOrSet(key K, val V, opts ...ItemOption) (actual V, loaded bool) {
228229
c.mu.Lock()
229230
defer c.mu.Unlock()
230231
item, ok := c.cache.Get(key)
231232

232233
if !ok || item.Expired() {
233234
item := newItem(key, val, opts...)
234235
c.cache.Set(key, item)
235-
return val
236+
return val, false
236237
}
237238

238-
return item.Value
239+
return item.Value, true
239240
}
240241

241242
// DeleteExpired all expired items from the cache.

example_test.go

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ import (
77

88
cache "github.com/Code-Hex/go-generics-cache"
99
"github.com/Code-Hex/go-generics-cache/policy/lfu"
10+
"github.com/Code-Hex/go-generics-cache/policy/lru"
1011
)
1112

1213
func ExampleCache() {
@@ -143,6 +144,19 @@ func ExampleCache_Contains() {
143144
// false
144145
}
145146

147+
func ExampleCache_GetOrSet() {
148+
c := cache.New(cache.AsLRU[string, int](lru.WithCapacity(10)))
149+
c.Set("a", 1)
150+
151+
val1, ok1 := c.GetOrSet("b", 2)
152+
fmt.Println(val1, ok1)
153+
val2, ok2 := c.GetOrSet("a", 3)
154+
fmt.Println(val2, ok2)
155+
// Output:
156+
// 2 false
157+
// 1 true
158+
}
159+
146160
func ExampleNewNumber() {
147161
nc := cache.NewNumber[string, int]()
148162
nc.Set("a", 1)

0 commit comments

Comments
 (0)