Pelago
Core typesInterfaces

eq

The eq interface: == and !=, which types have it already, and how to give an obj equality.

pub interface eq {
    fn eq(self, other: Self) -> bool
}

a == b and a != b need eq. Primitives, strings and collections have it; a plain struct or enum compares field by field and case by case, automatically. An obj does not: comparing two is the error ```ocannot be compared with==: it does not provide eq; write @derive(eq)onoorimpl eq for o` ``.

enum color { red, green }
struct tag { c: color, n: int }

obj thing { id: int }

impl eq for thing {
    fn eq(self, other: thing) -> bool = self.id == other.id
}

fn main() {
    print(color.red == color.red, color.red == color.green)
    print(tag { c: color.green, n: 2 } == tag { c: color.green, n: 2 })
    const a = thing { id: 1 }
    const b = thing { id: 1 }
    print(a == b, a != b)
}
true false
true
true false

!= is the opposite of eq; you never write it. Lists, maps and sets compare by value; maps and sets ignore order.

@derive(eq) writes the comparison for an obj, field by field, including nested lists, options and base-class fields.

Calling it as a method

a.eq(b) calls the comparison directly on any type that provides eq: numbers, bool, text, lists, structs and enums, and derived or hand-written objs. It gives the same answer as ==, and it also works on a value of a generic type with a bound, T: eq.

@derive(eq)
obj point {
    x: int
    y: int
}

fn same<T: eq>(a: T, b: T) -> bool = a.eq(b)

fn main() {
    const a = point { x: 1, y: 2 }
    print(a.eq(point { x: 1, y: 2 }), 3.eq(4), [1, 2].eq([1, 2]))
    print(same("x", "x"), same(4, 5))
}
true false true
true false

Interfaces, order, hash

On this page