Iterate through an OrderedMap
masterYou can iterate through the map in several ways depending on your Go version and desired direction.
Manual Iteration (Pointer-based)
For all Go versions, you can use Oldest() and Newest() to get a pointer to the first/last pair. Use .Next() to move forward or .Prev() to move backward. This is efficient as it allows breaking early without full traversal.
Native Iterator Support (Go >= 1.23)
If you are using Go 1.23 or later, you can use the range keyword with the following methods:
FromOldest(): Iterates pairs from oldest to newest.FromNewest(): Iterates pairs from newest to oldest.KeysFromOldest()/KeysFromNewest(): Iterates only the keys.ValuesFromOldest()/ValuesFromNewest(): Iterates only the values.
// Manual iteration (Oldest to Newest)
for pair := om.Oldest(); pair != nil; pair = pair.Next() {
fmt.Println(pair.Key, pair.Value)
}
// Manual iteration (Newest to Oldest)
for pair := om.Newest(); pair != nil; pair = pair.Prev() {
fmt.Println(pair.Key, pair.Value)
}
// Go 1.23+ range syntax
for k, v := range om.FromOldest() {
fmt.Println(k, v)
}