Track Bounded Evictions With container/list
Combine container/list with an index map to promote accessed entries in O(1) time and record evicted keys when inserting past max capacity.
Code
package main
import (
"container/list"
"fmt"
)
type item struct {
key string
val int
}
type BoundedTracker struct {
cap int
order *list.List
index map[string]*list.Element
evicted []string
}
func NewBoundedTracker(cap int) *BoundedTracker {
return &BoundedTracker{
cap: cap,
order: list.New(),
index: make(map[string]*list.Element, cap),
}
}
func (b *BoundedTracker) Touch(key string, val int) {
if b.cap <= 0 {
return
}
if el, ok := b.index[key]; ok {
el.Value.(*item).val = val
b.order.MoveToFront(el)
return
}
if b.order.Len() >= b.cap {
tail := b.order.Back()
old := b.order.Remove(tail).(*item)
delete(b.index, old.key)
b.evicted = append(b.evicted, old.key)
}
b.index[key] = b.order.PushFront(&item{key: key, val: val})
}
func main() {
tracker := NewBoundedTracker(3)
for i, k := range []string{"k1", "k2", "k3", "k1", "k4", "k5"} {
tracker.Touch(k, (i+1)*10)
}
fmt.Print("retained (MRU->LRU):")
for el := tracker.order.Front(); el != nil; el = el.Next() {
it := el.Value.(*item)
fmt.Printf(" %s=%d", it.key, it.val)
}
fmt.Println()
fmt.Println("evicted order:", tracker.evicted)
}Execution path — Track Bounded Evictions With container/list
Everything happens inside the functions NewBoundedTracker, Touch and main.
A single loop drives the file — for i, k := range []string{"k1", "k2", "k3", "k1", "k4", "k5"}.
What to watch for
- Runs on the standard library alone; nothing to install.
Using it
Inspection begins at signature func NewBoundedTracker(cap int) *BoundedTracker
Printed terminal lines display prefixes — retained (MRU->LRU):, evicted order: — when the file runs.
The demo flow inside main is NewBoundedTracker and Touch — run the file to see it end to end.
Key statements
for i, k := range []string{"k1", "k2", "k3", "k1", "k4", "k5"} {
tracker.Touch(k, (i+1)*10)
}
func NewBoundedTracker(cap int) *BoundedTracker {
return &BoundedTracker{
cap: cap,
order: list.New(),
index: make(map[string]*list.Element, cap),
}
}
b.evicted = append(b.evicted, old.key)
Interactive Tools for This Topic
cURL to Python & Go ConverterTranslate curl CLI commands with headers, auth, JSON bodies, and timeouts into ready-to-run Python requests and Go net/http client code snippets.HTTP Retry & Backoff CalculatorSimulate exponential backoff retry schedules with Full, Equal, Decorrelated, or No Jitter to inspect per-attempt wait times and cumulative latency.
FAQ
- What does Track Bounded Evictions With container/list print when run?
- Execute the whole file; each printed line is prefixed with a label like `retained (MRU->LRU):`, `evicted order:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.