Optimal, constant time implementation of ordered maps for Go with a simple API.
Supports modern range-over-function iteration via the standard library iter package.
Creating an ordered map uses any generic type K comparable, V any:
// equivalent of: make(map[string]int)
m := orderedmap.New[string, int]()You can specify an initial capacity hint:
// equivalent of: make(map[string]int, 1000)
m := orderedmap.WithCapacity[string, int](1000)Setting a value:
// equivalent of m["foo"] = 1
m.Set("foo", 1)Retrieving a value is equally simple, and uses the same bool ok secondary
return pattern to indicate whether a value was found in the map:
// equivalent of val, ok := m["foo"]
val, ok := m.Get("foo")The remaining operations mirror the standard library map:
m.Delete("foo") // equivalent of delete(m, "foo")
m.Clear() // equivalent of clear(m)
n := m.Len() // equivalent of len(m)You can simply range across the All() function, which will yield key value
pairs based on their insertion order:
for k, v := range m.All() {
fmt.Printf("k = %v, v = %v\n", k, v)
}See also Backward() to iterate from newest to oldest instead, as well as the
included Keys() and Values() iterators.
This module requires go1.24 or greater.
Upon my review, wk8/go-ordered-map appeared to be the best existing library, offering constant time operations and reasonable memory footprint. This module took some design cues from it. That said, there are some intentional design differences -- comparing this module with it, we optimize for:
- π Simpler API (less exposed surface area, similar to standard library maps).
- π± Reduced feature set (no built-in YAML serialization, for example).
- β¨ Use modern range-over-function expressions for easy iteration.
- β‘ Equally performant.
- 0οΈβ£ Zero dependencies.
As per other options, the README from wk8/go-ordered-map offers a summary:
- iancoleman/orderedmap only accepts
stringkeys, itsDeleteoperations are linear. - cevaris/ordered_map uses a channel for iterations, and leaks goroutines if the iteration is interrupted before fully traversing the map.
- mantyr/iterator also uses a channel for
iterations, and its
Deleteoperations are linear. - samdolan/go-ordered-map adds
unnecessary locking (users should add their own locking instead if they need
it), its
DeleteandGetoperations are linear, iterations trigger a linear memory allocation.