why can’t i use comparable constraints with order operators?

comparable is the constraint for types that support equality operators == and !=. The language spec defines this in Type constraints.

Notably, this includes anything that can be used as a map key, including arrays, structs with comparable fields but not interfaces.

It is true that in the Go language specifications, the comparison operators include order operators as (<, >, <=, >=). This choice of terminology probably is what confuses you. However the specs also disambiguate:

The equality operators == and != apply to operands that are comparable. The ordering operators <, <=, >, and >= apply to operands that are ordered.

In Go 1.18 the available constraint that supports the order operators such as > and < is constraints.Ordered1:

type Ordered interface {
    Integer | Float | ~string

1: note that the package golang.org/x/exp is experimental. Its contents aren’t guaranteed to be backwards compatible with new Go releases, but you can always copy-paste the definitions you need into your own code

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top