Problem:
When using a generically-defined linked list as a map key in Go 1.18, an error message appears indicating that the linked list does not implement the comparable interface. Is there a weaker alternative constraint suitable for this purpose?
Answer:
Go 1.20 (February 2023)
The comparable constraint is the appropriate catch-all constraint for map keys. In Go 1.20, the inconsistency between spec-comparable and comparable types is resolved, allowing your code to compile successfully.
Go 1.18 and 1.19
The comparable constraint in Go 1.18 and 1.19 is designed for strictly comparable types that support == and != without runtime panics. This excludes interfaces, even those that do support equality operators. Since interfaces have an infinite type set, they cannot be instantiated as comparable.
To address this, consider using a custom constraint that embeds comparable, such as:
type List interface { comparable isList() bool }
Structurally implementing this constraint would allow the linked list to be used as a map key.
The above is the detailed content of Can Go Generics' `comparable` Constraint Be Weakened for Map Keys in Pre-1.20 Versions?. For more information, please follow other related articles on the PHP Chinese website!