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
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.Controls what happens when you
Store a key that already exists.true— stable mode: the key keeps its original insertion position in the order. Useful when you care about when a key first appeared.false— recency 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
| Method | Signature | Description |
|---|---|---|
Store | Store(key K, value V) | Inserts or updates a key-value pair. In recency mode, updates an existing key’s position to the end. |
Load | Load(key K) (value V, loaded bool) | Returns the value for a key. loaded is false if the key is absent. |
Delete | Delete(key K) | Removes a key and its value. No-op if the key is absent. |
Range | Range(func(key K, value V) bool) | Iterates over all entries in insertion/recency order. Return false from the callback to stop early. |
Len | Len() int | Returns the number of entries currently in the map. |
Stable vs. recency mode
- stable=true (insertion order)
- stable=false (recency order)
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).