(I started a conversation on Twitter but @adg suggested it would be a good time to try out this forum.)
@adg has advised in the past that it isn’t a good idea to use interface types as map keys because if an implementation is provided which has an incomparable type (map, slice, func), it will result in a runtime panic.
This is of course sensible and I agree in general, but I’ve also found cases where I’m not easily able to avoid using an interface in a map key. The one that comes to mind at the moment is when making use of http.ConnState callback. Sometimes I’ve used that to get statistics on the number of connections in various states, and in that case I’ve used c.RemoteAddr() as my map key. But at other times, it’s more natural to use net.Conn itself as the key. See, for example, @bradfitz’s recent CL for net/http/httptest:
In my point of view, there is always a chance you have runtime panic even if you’re writing code that you feel most comfortable with. Also, things can be worked around to reduce the probabilities of runtime panic such as do a type check before using it to access value in the map.
I considered that problem when I wrote that code but I realized in this case, all net.Conn cases are from net.Listener (newLocalListener in that file), so it’s safe.
The problem is: you have a net.Conn that you want to use as a map key. If it’s a *net.conn, then that’s safe; if it’s some other concrete type, then it might not be.
How do you check whether the net.Conn is a *net.conn?
What do you do if it isn’t?
I’m claiming that if you care about protecting yourself from this problem, the solution is to not use a net.Conn as a map key at all.
This is really a matter of context. Who will be using the map? How will the map be accessible? What might you be using as a key (concrete types)? Where are those types coming from (are you writing them, 3rd party lib)? Who else will be working with this code (will they recognize the same concerns when making changes)?
If the surface area is really small, I wouldn’t fret over it. Otherwise, why risk it.