Table of Contents
✅ Key Components
? Step-by-step Implementation
✅ Example Usage
? Thread Safety
⚙️ Performance
? Notes
Home Backend Development Golang How to implement a generic LRU cache in Go

How to implement a generic LRU cache in Go

Aug 18, 2025 am 08:31 AM
go lru cache

Use Go generics and container/list to achieve thread-safe LRU cache; 2. Core components include maps, bidirectional linked lists and mutex locks; 3. Get and Add operations ensure concurrency security through locks, with a time complexity of O(1); 4. Automatically eliminate the longest unused entry when the cache is full; 5. In the example, the cache with capacity of 3 successfully eliminates the longest unused "b". This implementation fully supports generic, efficient and scalable.

How to implement a generic LRU cache in Go

Implementing a generic LRU (Least Recently Used) cache in Go is straightforward using Go's built-in data structures and the container/list package. With Go 1.18 generics, you can create a reusable LRU cache that works with any key and value types, as long as the key is comparable.

How to implement a generic LRU cache in Go

Here's how to build a thread-safe, generic LRU cache:


✅ Key Components

We'll use:

How to implement a generic LRU cache in Go
  • map[K]*list.Element — to store key-to-node mapping for O(1) access.
  • list.List — a double-linked list to maintain access order (most recently used at back, least at front).
  • A sync.Mutex — for thread safety.
  • Generics — to allow any comparable key type K and any value type V .

? Step-by-step Implementation

 package main

import (
    "container/list"
    "sync"
)

// LRUCache is a generic LRU cache.
type LRUCache[K comparable, V any] struct {
    capacity int
    cache map[K]*list.Element
    ll *list.List // double-linked list to track order
    mu sync.Mutex
}

// entry is a key-value pair stored in the list
type entry[K comparable, V any] struct {
    key K
    value V
}

// NewLRUCache creates a new LRU cache with the given capacity.
func NewLRUCache[K comparable, V any](capacity int) *LRUCache[K, V] {
    return &LRUCache[K, V]{
        capacity: capacity,
        cache: make(map[K]*list.Element),
        ll: list.New(),
    }
}

// Get retrieves a value by key. Returns value and true if found.
func (c *LRUCache[K, V]) Get(key K) (V, bool) {
    c.mu.Lock()
    defer c.mu.Unlock()

    var zero V
    elem, exists := c.cache[key]
    if !exists {
        return zero, false
    }

    // Move the accessed element to the back (most recently used)
    c.ll.MoveToBack(elem)
    return elem.Value.(*entry[K, V]).value, true
}

// Add inserts a key-value pair into the cache.
// If the key exists, it updates the value and marks it as recently used.
// If the cache is full, it evils the least recently used item.
func (c *LRUCache[K, V]) Add(key K, value V) {
    c.mu.Lock()
    defer c.mu.Unlock()

    if elem, exists := c.cache[key]; exists {
        // Update value and move to back
        elem.Value.(*entry[K, V]).value = value
        c.ll.MoveToBack(elem)
        Return
    }

    // Add new element to the back
    newElem := c.ll.PushBack(&entry[K, V]{key: key, value: value})
    c.cache[key] = newElem

    // Evict if over capacity
    if c.ll.Len() > c.capacity {
        c.evict()
    }
}

// evict removes the least recently used item (front of list)
func (c *LRUCache[K, V]) evict() {
    if elem := c.ll.Front(); elem != nil {
        c.ll.Remove(elem)
        key := elem.Value.(*entry[K, V]).key
        delete(c.cache, key)
    }
}

// Len returns the current number of items in the cache.
func (c *LRUCache[K, V]) Len() int {
    c.mu.Lock()
    defer c.mu.Unlock()
    return c.ll.Len()
}

✅ Example Usage

 func main() {
    cache := NewLRUCache[string, int](3)

    cache.Add("a", 1)
    cache.Add("b", 2)
    cache.Add("c", 3)

    // Access "a" → moves to back (most recently used)
    if val, ok := cache.Get("a"); ok {
        println("Got:", val) // Got: 1
    }

    // Add "d" → should evict "b" ( least recently used)
    cache.Add("d", 4)

    // Check contents
    if _, ok := cache.Get("b"); !ok {
        println("b was evicted")
    }
    if _, ok := cache.Get("a"); ok {
        println("a still exists")
    }
    if _, ok := cache.Get("d"); ok {
        println("d exists")
    }
}

? Thread Safety

The cache is thread-safe due to the sync.Mutex . All operations are protected by a mutex lock. For high-concurrency use, consider using RWMutex (read-write mutex) to allow concurrent reads.


⚙️ Performance

  • Get : O(1)
  • Add : O(1)
  • Eviction : O(1)

This makes it efficient for most practical use cases.

How to implement a generic LRU cache in Go

? Notes

  • The key type K must be comparable (required by Go maps).
  • The value type V can be any type ( any ).
  • You can extend this with features like TTL (time-to-live), callbacks on eviction, or size-based eviction.

That's it. You now have a clean, generic, thread-safe LRU cache in Go.

The above is the detailed content of How to implement a generic LRU cache in Go. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

PHP Tutorial
1596
276
How do you work with environment variables in Golang? How do you work with environment variables in Golang? Aug 19, 2025 pm 02:06 PM

Goprovidesbuilt-insupportforhandlingenvironmentvariablesviatheospackage,enablingdeveloperstoread,set,andmanageenvironmentdatasecurelyandefficiently.Toreadavariable,useos.Getenv("KEY"),whichreturnsanemptystringifthekeyisnotset,orcombineos.Lo

How to create and use custom error types in Go How to create and use custom error types in Go Aug 11, 2025 pm 11:08 PM

In Go, creating and using custom error types can improve the expressiveness and debugability of error handling. The answer is to create a custom error by defining a structure that implements the Error() method. For example, ValidationError contains Field and Message fields and returns formatted error information. The error can then be returned in the function, detecting specific error types through type assertions or errors.As to execute different logic. You can also add behavioral methods such as IsCritical to custom errors, which are suitable for scenarios that require structured data, differentiated processing, library export or API integration. In simple cases, errors.New, and predefined errors such as ErrNotFound can be used for comparable

How to implement a generic LRU cache in Go How to implement a generic LRU cache in Go Aug 18, 2025 am 08:31 AM

Use Go generics and container/list to achieve thread-safe LRU cache; 2. The core components include maps, bidirectional linked lists and mutex locks; 3. Get and Add operations ensure concurrency security through locks, with a time complexity of O(1); 4. When the cache is full, the longest unused entry will be automatically eliminated; 5. In the example, the cache with capacity of 3 successfully eliminated the longest unused "b". This implementation fully supports generic, efficient and scalable.

How do you handle signals in a Go application? How do you handle signals in a Go application? Aug 11, 2025 pm 08:01 PM

The correct way to process signals in Go applications is to use the os/signal package to monitor the signal and perform elegant shutdown. 1. Use signal.Notify to send SIGINT, SIGTERM and other signals to the channel; 2. Run the main service in goroutine and block the waiting signal; 3. After receiving the signal, perform elegant shutdown with timeout through context.WithTimeout; 4. Clean up resources such as closing database connections and stopping background goroutine; 5. Use signal.Reset to restore the default signal behavior when necessary to ensure that the program can be reliably terminated in Kubernetes and other environments.

How to use path/filepath for cross-platform path manipulation in Go How to use path/filepath for cross-platform path manipulation in Go Aug 08, 2025 pm 05:29 PM

Usefilepath.Join()tosafelyconstructpathswithcorrectOS-specificseparators.2.Usefilepath.Clean()toremoveredundantelementslike".."and".".3.Usefilepath.Split()toseparatedirectoryandfilecomponents.4.Usefilepath.Dir(),filepath.Base(),an

How do you define and call a function in Go? How do you define and call a function in Go? Aug 14, 2025 pm 06:22 PM

In Go, defining and calling functions use the func keyword and following fixed syntax, first clarify the answer: the function definition must include name, parameter type, return type and function body, and pass in corresponding parameters when calling; 1. Use funcfunctionName(params) returnType{} syntax when defining functions, such as funcadd(a,bint)int{return b}; 2. Support multiple return values, such as funcdivide(a,bfloat64)(float64,bool){}; 3. Calling functions directly uses the function name with brackets to pass parameters, such as result:=add(3,5); 4. Multiple return values can be received by variables or

Performance Comparison: Java vs. Go for Backend Services Performance Comparison: Java vs. Go for Backend Services Aug 14, 2025 pm 03:32 PM

Gotypicallyoffersbetterruntimeperformancewithhigherthroughputandlowerlatency,especiallyforI/O-heavyservices,duetoitslightweightgoroutinesandefficientscheduler,whileJava,thoughslowertostart,canmatchGoinCPU-boundtasksafterJIToptimization.2.Gouseslessme

Parsing RSS and Atom Feeds in a Go Application Parsing RSS and Atom Feeds in a Go Application Aug 18, 2025 am 02:40 AM

Use the gofeed library to easily parse RSS and Atomfeed. First, install the library through gogetgithub.com/mmcdole/gofeed, then create a Parser instance and call the ParseURL or ParseString method to parse remote or local feeds. The library will automatically recognize the format and return a unified feed structure. Then iterate over feed.Items to get standardized fields such as title, link, and publishing time. It is also recommended to set HTTP client timeouts, handle parsing errors, and use cache optimization performance to ultimately achieve simple, efficient and reliable feed resolution.

See all articles