Go Generics: Type Constraints for Map Keys
Question:
Why does the following code fail to compile when using a generic linked list as a map key?
Answer:
In Go 1.18 and 1.19, the predeclared comparable constraint is required for map keys, and it restricts usage to strictly comparable types that support == and != comparisons without panicking at runtime. Interfaces, even though they support equality comparisons, do not implement comparable because they have an infinite type set.
While the List[X] interface itself can be used as a map key, the Cons[X] struct does not implement comparable because it contains a List[X] field. There is no weaker constraint that can be used to identify types suitable for use as map keys.
However, in Go 1.20 (February 2023), this behavior has been fixed. comparable now accepts all types that are comparable according to the language specification, even if they may panic at runtime due to the comparison. This allows the code to compile successfully.
Alternative Constraint:
If it is necessary to use a constraint that includes the isList() method, you can define your own constraint as follows:
Then, have your map key structs implement this List interface instead of declaring an interface field.
The above is the detailed content of Why Can't Generic Linked Lists Be Used as Map Keys in Go (Prior to 1.20)?. For more information, please follow other related articles on the PHP Chinese website!