golang / go

The Go programming language
https://go.dev
BSD 3-Clause "New" or "Revised" License
124.04k stars 17.67k forks source link

proposal: container: add generic ordered map #53196

Open rcoreilly opened 2 years ago

rcoreilly commented 2 years ago

This proposal is just to suggest that an official implementation of an ordered map using the new generics would likely be a widely-appreciated addition to the standard library.

Personally, it took me a while to realize that I was constantly writing some version or another of an ordered map. Now that I've made my own generic version, I've used it several times.

My version is here: https://github.com/goki/kigen/tree/main/ordmap

And here is another example: https://github.com/wk8/go-ordered-map

My version is more "bare metal" and exposes all the impl, so you can add functionality etc as needed, and use standard Go range iteration on the slice or map. It just saves you the effort of keeping the map and slice coordinated when deleting or inserting.

The other example provides iterator functions instead, and hides the impl.

Obviously, anyone can roll their own as desired, but there might be some benefit to having a standard impl with the incomparable design sensibilities of the Go team. Again, the only real point here is to suggest that such a thing would likely be widely used and appreciated..

In any case, this is also an opportunity to provide glowing positive feedback for what a pleasure it was to finally use the generics after all those debates etc -- everything was very intuitive, and I have not noticed either of the two evils of generics slowdowns (though I haven't done any benchmarking). Great job!

ps. did I miss it or is a generic version of Min and Max not yet avail? That was prominent in the original discussions, but I searched under issues here and didn't find discussion of it.

ianlancetaylor commented 2 years ago

This is the kind of package that we normally suggest should be created outside the standard library, and it sounds like that is already happening. When a package becomes popular we can consider bringing it in.

earthboundkid commented 2 years ago

ps. did I miss it or is a generic version of Min and Max not yet avail? That was prominent in the original discussions, but I searched under issues here and didn't find discussion of it.

The decision was made to wait until the dust settles before adding a lot of generics to the standard library. There's discussion mentioning math.Min/Max at https://github.com/golang/go/discussions/48287.

I think something like this proposal makes sense as part of rethinking of the container types: deque, sets, ordered map, a generic heap, possibly others…