Skip to content

Commit eab552f

Browse files
committed
refactor: Replace interface{} by any
1 parent 268181c commit eab552f

File tree

6 files changed

+43
-40
lines changed

6 files changed

+43
-40
lines changed

README.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -131,7 +131,7 @@ func main() {
131131

132132
cache.Set("key", "value")
133133
cache.SetWithTTL("key-with-ttl", "value", 60*time.Minute)
134-
cache.SetAll(map[string]interface{}{"k1": "v1", "k2": "v2", "k3": "v3"})
134+
cache.SetAll(map[string]any{"k1": "v1", "k2": "v2", "k3": "v3"})
135135

136136
fmt.Println("[Count] Cache size:", cache.Count())
137137

entry.go

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@ type Entry struct {
1212
Key string
1313

1414
// Value is the value of the cache entry
15-
Value interface{}
15+
Value any
1616

1717
// RelevantTimestamp is the variable used to store either:
1818
// - creation timestamp, if the Cache's EvictionPolicy is FirstInFirstOut
@@ -48,7 +48,7 @@ func (entry *Entry) SizeInBytes() int {
4848
return toBytes(entry.Key) + toBytes(entry.Value) + 32
4949
}
5050

51-
func toBytes(value interface{}) int {
51+
func toBytes(value any) int {
5252
switch value.(type) {
5353
case string:
5454
return int(unsafe.Sizeof(value)) + len(value.(string))
@@ -60,9 +60,9 @@ func toBytes(value interface{}) int {
6060
return int(unsafe.Sizeof(value)) + 4
6161
case int64, uint64, int, uint, float64, complex128:
6262
return int(unsafe.Sizeof(value)) + 8
63-
case []interface{}:
63+
case []any:
6464
size := 0
65-
for _, v := range value.([]interface{}) {
65+
for _, v := range value.([]any) {
6666
size += toBytes(v)
6767
}
6868
return int(unsafe.Sizeof(value)) + size

entry_test.go

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -62,10 +62,10 @@ func TestEntry_SizeInBytes(t *testing.T) {
6262
testSizeInBytes(t, "k", struct{ A string }{A: "hello"}, 72)
6363
testSizeInBytes(t, "k", struct{ A, B string }{A: "hello", B: "world"}, 78)
6464
testSizeInBytes(t, "k", nil, 70)
65-
testSizeInBytes(t, "k", make([]interface{}, 5), 170)
65+
testSizeInBytes(t, "k", make([]any, 5), 170)
6666
}
6767

68-
func testSizeInBytes(t *testing.T, key string, value interface{}, expectedSize int) {
68+
func testSizeInBytes(t *testing.T, key string, value any, expectedSize int) {
6969
t.Run(fmt.Sprintf("%T_%d", value, expectedSize), func(t *testing.T) {
7070
if size := (&Entry{Key: key, Value: value}).SizeInBytes(); size != expectedSize {
7171
t.Errorf("expected size of entry with key '%v' and value '%v' (%T) to be %d, got %d", key, value, value, expectedSize, size)

gocache.go

Lines changed: 30 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -165,25 +165,27 @@ func (cache *Cache) WithEvictionPolicy(policy EvictionPolicy) *Cache {
165165
// is nil or not.
166166
//
167167
// If set to true (default):
168-
// cache := gocache.NewCache().WithForceNilInterfaceOnNilPointer(true)
169-
// cache.Set("key", (*Struct)(nil))
170-
// value, _ := cache.Get("key")
171-
// // the following returns true, because the interface{} was forcefully set to nil
172-
// if value == nil {}
173-
// // the following will panic, because the value has been casted to its type (which is nil)
174-
// if value.(*Struct) == nil {}
168+
//
169+
// cache := gocache.NewCache().WithForceNilInterfaceOnNilPointer(true)
170+
// cache.Set("key", (*Struct)(nil))
171+
// value, _ := cache.Get("key")
172+
// // the following returns true, because the interface{} (any) was forcefully set to nil
173+
// if value == nil {}
174+
// // the following will panic, because the value has been casted to its type (which is nil)
175+
// if value.(*Struct) == nil {}
175176
//
176177
// If set to false:
177-
// cache := gocache.NewCache().WithForceNilInterfaceOnNilPointer(false)
178-
// cache.Set("key", (*Struct)(nil))
179-
// value, _ := cache.Get("key")
180-
// // the following returns false, because the interface{} returned has a non-nil type (*Struct)
181-
// if value == nil {}
182-
// // the following returns true, because the value has been casted to its type
183-
// if value.(*Struct) == nil {}
178+
//
179+
// cache := gocache.NewCache().WithForceNilInterfaceOnNilPointer(false)
180+
// cache.Set("key", (*Struct)(nil))
181+
// value, _ := cache.Get("key")
182+
// // the following returns false, because the interface{} (any) returned has a non-nil type (*Struct)
183+
// if value == nil {}
184+
// // the following returns true, because the value has been cast to its type
185+
// if value.(*Struct) == nil {}
184186
//
185187
// In other words, if set to true, you do not need to cast the value returned from the cache to
186-
// to check if the value is nil.
188+
// check if the value is nil.
187189
//
188190
// Defaults to true
189191
func (cache *Cache) WithForceNilInterfaceOnNilPointer(forceNilInterfaceOnNilPointer bool) *Cache {
@@ -194,8 +196,8 @@ func (cache *Cache) WithForceNilInterfaceOnNilPointer(forceNilInterfaceOnNilPoin
194196
// NewCache creates a new Cache
195197
//
196198
// Should be used in conjunction with Cache.WithMaxSize, Cache.WithMaxMemoryUsage and/or Cache.WithEvictionPolicy
197-
// gocache.NewCache().WithMaxSize(10000).WithEvictionPolicy(gocache.LeastRecentlyUsed)
198199
//
200+
// gocache.NewCache().WithMaxSize(10000).WithEvictionPolicy(gocache.LeastRecentlyUsed)
199201
func NewCache() *Cache {
200202
return &Cache{
201203
maxSize: DefaultMaxSize,
@@ -209,15 +211,15 @@ func NewCache() *Cache {
209211
}
210212

211213
// Set creates or updates a key with a given value
212-
func (cache *Cache) Set(key string, value interface{}) {
214+
func (cache *Cache) Set(key string, value any) {
213215
cache.SetWithTTL(key, value, NoExpiration)
214216
}
215217

216218
// SetWithTTL creates or updates a key with a given value and sets an expiration time (-1 is NoExpiration)
217219
//
218220
// The TTL provided must be greater than 0, or NoExpiration (-1). If a negative value that isn't -1 (NoExpiration) is
219221
// provided, the entry will not be created if the key doesn't exist
220-
func (cache *Cache) SetWithTTL(key string, value interface{}, ttl time.Duration) {
222+
func (cache *Cache) SetWithTTL(key string, value any, ttl time.Duration) {
221223
// An interface is only nil if both its value and its type are nil, however, passing a nil pointer as an interface{}
222224
// means that the interface itself is not nil, because the interface value is nil but not the type.
223225
if cache.forceNilInterfaceOnNilPointer {
@@ -298,7 +300,7 @@ func (cache *Cache) SetWithTTL(key string, value interface{}, ttl time.Duration)
298300
}
299301

300302
// SetAll creates or updates multiple values
301-
func (cache *Cache) SetAll(entries map[string]interface{}) {
303+
func (cache *Cache) SetAll(entries map[string]any) {
302304
for key, value := range entries {
303305
cache.SetWithTTL(key, value, NoExpiration)
304306
}
@@ -307,7 +309,7 @@ func (cache *Cache) SetAll(entries map[string]interface{}) {
307309
// Get retrieves an entry using the key passed as parameter
308310
// If there is no such entry, the value returned will be nil and the boolean will be false
309311
// If there is an entry, the value returned will be the value cached and the boolean will be true
310-
func (cache *Cache) Get(key string) (interface{}, bool) {
312+
func (cache *Cache) Get(key string) (any, bool) {
311313
cache.mutex.Lock()
312314
entry, ok := cache.get(key)
313315
if !ok {
@@ -337,7 +339,7 @@ func (cache *Cache) Get(key string) (interface{}, bool) {
337339

338340
// GetValue retrieves an entry using the key passed as parameter
339341
// Unlike Get, this function only returns the value
340-
func (cache *Cache) GetValue(key string) interface{} {
342+
func (cache *Cache) GetValue(key string) any {
341343
value, _ := cache.Get(key)
342344
return value
343345
}
@@ -346,8 +348,8 @@ func (cache *Cache) GetValue(key string) interface{} {
346348
// All keys are returned in the map, regardless of whether they exist or not, however, entries that do not exist in the
347349
// cache will return nil, meaning that there is no way of determining whether a key genuinely has the value nil, or
348350
// whether it doesn't exist in the cache using only this function.
349-
func (cache *Cache) GetByKeys(keys []string) map[string]interface{} {
350-
entries := make(map[string]interface{})
351+
func (cache *Cache) GetByKeys(keys []string) map[string]any {
352+
entries := make(map[string]any)
351353
for _, key := range keys {
352354
entries[key], _ = cache.Get(key)
353355
}
@@ -365,8 +367,8 @@ func (cache *Cache) GetByKeys(keys []string) map[string]interface{} {
365367
// GetKeysByPattern is a good alternative if you want to retrieve entries that you do not have the key for, as it only
366368
// retrieves the keys and does not trigger active eviction and has a parameter for setting a limit to the number of keys
367369
// you wish to retrieve.
368-
func (cache *Cache) GetAll() map[string]interface{} {
369-
entries := make(map[string]interface{})
370+
func (cache *Cache) GetAll() map[string]any {
371+
entries := make(map[string]any)
370372
cache.mutex.Lock()
371373
for key, entry := range cache.entries {
372374
if entry.Expired() {
@@ -385,8 +387,9 @@ func (cache *Cache) GetAll() map[string]interface{} {
385387
// If the limit is above 0, the search will stop once the specified number of matching keys have been found.
386388
//
387389
// e.g.
388-
// cache.GetKeysByPattern("*some*", 0) will return all keys containing "some" in them
389-
// cache.GetKeysByPattern("*some*", 5) will return 5 keys (or less) containing "some" in them
390+
//
391+
// cache.GetKeysByPattern("*some*", 0) will return all keys containing "some" in them
392+
// cache.GetKeysByPattern("*some*", 5) will return 5 keys (or less) containing "some" in them
390393
//
391394
// Note that GetKeysByPattern does not trigger active evictions, nor does it count as accessing the entry (if LRU).
392395
// The reason for that behavior is that these two (active eviction and access) only applies when you access the value

gocache_bench_test.go

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@ import (
99
)
1010

1111
func BenchmarkMap_Get(b *testing.B) {
12-
m := make(map[string]interface{})
12+
m := make(map[string]any)
1313
for n := 0; n < b.N; n++ {
1414
_, _ = m[strconv.Itoa(n)]
1515
}
@@ -24,7 +24,7 @@ func BenchmarkMap_Set(b *testing.B) {
2424
}
2525
for name, value := range values {
2626
b.Run(fmt.Sprintf("%s value", name), func(b *testing.B) {
27-
m := make(map[string]interface{})
27+
m := make(map[string]any)
2828
for n := 0; n < b.N; n++ {
2929
m[strconv.Itoa(n)] = value
3030
}

gocache_test.go

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -336,7 +336,7 @@ func TestCache_SetGetStruct(t *testing.T) {
336336

337337
func TestCache_SetAll(t *testing.T) {
338338
cache := NewCache().WithMaxSize(NoMaxSize)
339-
cache.SetAll(map[string]interface{}{"k1": "v1", "k2": "v2"})
339+
cache.SetAll(map[string]any{"k1": "v1", "k2": "v2"})
340340
value, ok := cache.Get("k1")
341341
if !ok {
342342
t.Error("expected key to exist")
@@ -351,7 +351,7 @@ func TestCache_SetAll(t *testing.T) {
351351
if value != "v2" {
352352
t.Errorf("expected: %s, but got: %s", "v2", value)
353353
}
354-
cache.SetAll(map[string]interface{}{"k1": "updated"})
354+
cache.SetAll(map[string]any{"k1": "updated"})
355355
value, ok = cache.Get("k1")
356356
if !ok {
357357
t.Error("expected key to exist")
@@ -949,7 +949,7 @@ func TestCache_MemoryUsageIsReliable(t *testing.T) {
949949
t.Error("cache.MemoryUsage() should've increased")
950950
}
951951
previousCacheMemoryUsage = cache.MemoryUsage()
952-
cache.SetAll(map[string]interface{}{"2": "2", "3": "3", "4": "4"})
952+
cache.SetAll(map[string]any{"2": "2", "3": "3", "4": "4"})
953953
if cache.MemoryUsage() <= previousCacheMemoryUsage {
954954
t.Error("cache.MemoryUsage() should've increased")
955955
}
@@ -1003,7 +1003,7 @@ func TestCache_WithForceNilInterfaceOnNilPointer(t *testing.T) {
10031003
t.Error("expected key to exist")
10041004
} else {
10051005
if value != nil {
1006-
// the value is not nil, because cache.Get returns an interface{}, and the type of that interface is not nil
1006+
// the value is not nil, because cache.Get returns an interface{} (any), and the type of that interface is not nil
10071007
t.Error("value should be nil")
10081008
}
10091009
}

0 commit comments

Comments
 (0)