Skip to main content
OrderedMap is a generic key-value map that guarantees iteration order. Unlike Go’s built-in map, which randomizes iteration, OrderedMap lets you control whether order is stable (insertion order, even after updates) or recency-based (most recently written key comes last — useful for LRU caches).

Installation

Constructor

int
required
A hint for the initial capacity of the internal slice and map. Use 0 if you have no estimate. This does not limit the maximum size.
bool
required
Controls what happens when you Store a key that already exists.
  • truestable mode: the key keeps its original insertion position in the order. Useful when you care about when a key first appeared.
  • falserecency mode: the key is moved to the end of the order on every write. Useful for LRU caches where the most recently touched entry should appear last.

Methods

Range may panic if the callback deletes map entries during iteration. Avoid modifying the map inside the callback.

Stable vs. recency mode

The key’s position is fixed at the time of first insertion. Subsequent Store calls for the same key update the value but leave the order unchanged.

Example

The following example inserts eight entries, deletes one, updates another, then iterates over the result in order.

Checking for a key before acting

Load returns a boolean so you can distinguish a missing key from a key that maps to the zero value:
OrderedMap is not concurrency-safe. If multiple goroutines need to read or write the same map concurrently, add external synchronization (for example, a sync.RWMutex).