Skip to content
Playground(another site)

Declare `Eq` on a generic that compares

Do this when a generic function or method compares values of its type parameter with == or !=, or passes the parameter to another generic that does. The compiler says exactly where, and offers the fix.

Add : Eq to the parameter:

commons guide.same
fn same[T: Eq](a: T, b: T) -> Bool {
a == b
}
fn twice[U: Eq](a: U, b: U) -> Bool {
same(a, b)
}

twice never writes == itself, but it hands U to same, whose T is Eq, so U must be declared Eq as well.

A method compares the receiver type’s parameter, which it does not declare. Bound it with a where clause after the return type:

commons guide.boxes
type Box[A] = {
value: A,
}
fn Box.has(self, x: A) -> Bool where A: Eq {
self.value == x
}

bynk.generics.missing_eq_bound carries a machine-applicable fix. In an editor it is a quick fix, and Fix all (source.fixAll.bynk) applies every one in the file in a single action. One pass reports every link of a chain of generics (across units too), so one fix-all adds them all; a method that compares two receiver type parameters may need a second pass, since both fixes extend the same where clause.

Without an editor, bynk check --fix (#2642) applies the same fixes from the command line, repeating until none is left.

A call is checked against the declared bound. same(f, h) on two functions fails at the call, because functions are not equality-supporting, and the signature says so up front (hover on same shows [T: Eq]). A generic that never compares its parameter stays unbounded and keeps accepting functions.

Reference: Generics and bounds. If you are upgrading older code, see bynk.generics.missing_eq_bound.