Add sorted Map and Set types ordered by key (experimental)
Go has no standard container that keeps keys in sorted order. Many projects write their own tree map or ordered set. Similar types exist in other languages, such as C++ std::map, Java SortedMap, and Rust BTreeMap.
The proposal adds a new package, golang.org/x/exp/collection/sorted, with generic Map[K, V] and Set[T] types. Both are created with a comparison function (such as cmp.Compare) that defines the order. They support insert, lookup, delete, min and max, access by index, and iteration in ascending or descending order. Range queries use span types (MapSpan and SetSpan) that cover the part of the collection between optional bounds.
m := sorted.NewMap[string, int](cmp.Compare)
m.Set("cherry", 7)
m.Set("apple", 5)
m.Set("banana", 3)
for k, v := range m.All() {
fmt.Println(k, v)
}
// apple 5
// banana 3
// cherry 7
// Keys from "b" (inclusive) to "c" (exclusive).
for k := range m.From("b").Below("c").Keys() {
fmt.Println(k)
}
// banana
- Proposal
- #60630 by leaxoy
- Status
- Accepted on Nov 11, 2026
- Impact
- medium
- Area
- x/exp/collection/sorted