Go Generics: Type Constraints for Map Keys
In Go1.18, defining a generic linked list that can be used as a map key fails with the error "Cons[int] does not implement comparable." This is due to the strict requirement for map keys to implement the comparable interface, which ensures they support equality checks (== and !=) without panicking.
Go 1.20 Update
In Go 1.20, the comparable constraint is now considered the correct catch-all for map keys. Types that are considered comparable according to the Go spec, even if comparisons may panic, will satisfy the constraint. This resolves the inconsistency between types that are comparable according to the spec and those that are strictly comparable.
Go 1.18 and 1.19 Considerations
In Go 1.18 and 1.19, the comparable constraint could only be instantiated by strictly comparable types that support == and != without panicking. This excluded interfaces. Despite supporting the equality operators, interfaces didn't implement comparable because their dynamic types and values were compared. This meant that the provided Cons struct, which contained a field of type List[X], couldn't implement comparable.
Alternative Constraint
To address this limitation, a custom constraint that embeds comparable could be defined and implemented by map-key structs instead of using an interface field. For example:
type List interface { comparable isList() bool }
In conclusion, the comparable constraint is now the recommended type constraint for map keys in Go 1.20. In Go 1.18 and 1.19, interfaces could not be instantiated with comparable due to their infinite type set. Custom constraints that embed comparable could be used as alternatives.
The above is the detailed content of How Have Go's Type Constraints for Map Keys Evolved Across Versions 1.18, 1.19, and 1.20?. For more information, please follow other related articles on the PHP Chinese website!