LRU Cache
Thread-safe LRU (Least Recently Used) cache implementation in Go with generics.
Installation
go get github.com/elcruzo/lru-cache
Usage
package main
import (
"fmt"
lru "github.com/elcruzo/lru-cache"
)
func main() {
cache := lru.New[string, int](100)
cache.Put("a", 1)
cache.Put("b", 2)
if val, ok := cache.Get("a"); ok {
fmt.Println(val) // 1
}
cache.Delete("b")
cache.Clear()
}
API
| Method |
Description |
New[K, V](capacity) |
Create cache with capacity |
Get(key) |
Get value, returns (value, exists) |
Put(key, value) |
Add or update entry |
Delete(key) |
Remove entry |
Len() |
Current size |
Cap() |
Maximum capacity |
Clear() |
Remove all entries |
Keys() |
Get all keys (most recent first) |
Features
- Generic types (Go 1.18+)
- Thread-safe with RWMutex
- O(1) get/put operations
- Automatic eviction of least recently used items
License
MIT License - see LICENSE for details.