Browse the docs

silk.core.equal.

The interface that gives user types the == and != operators.

When to use#

Implement Equal when values of a type can be compared for equality with ==. Add a T: Equal bound when a generic function compares its type parameter.

Details#

&left == &right means Equal.equals(&left, &right) for the conformance of the operand type. &left != &right is the negation (OP-009). The operators borrow both operands, so a comparison does not consume a value. Concrete scalar and string operands always use the built-in operators.

Gotchas#

A conformance must be reflexive, symmetric, and transitive. The compiler does not check these rules. Generic code that uses == gives incorrect results if the rules are not true.

Examples#

Compare two values of a user type#

silk
import silk.core.equal { Equal }

struct Point {
  x: i32,
  y: i32,
}

fn samePoint(left: &Point, right: &Point) -> bool {
  return left.x == right.x && left.y == right.y
}

impl Equal for Point {
  equals: Point.samePoint
}

pub fn main() -> i32 {
  let first = Point { x: 1, y: 2 }
  let second = Point { x: 1, y: 2 }
  if &first != &second {
    return 1
  }
  return 0
}

Import as Equal with import silk.core.equal { Equal }.

Public declarations: 1.

Equal#

silk
pub type Equal = Intrinsic.Equal

The interface behind == and !=.

Details#

A conformance impl Equal for T gives the member equals(left: &T, right: &T) -> bool. The operators borrow both operands, so a comparison does not consume a value.

The integer types, f32, f64, bool, char, and string implement it with the built-in ==. string compares its UTF-8 bytes exactly.

Gotchas#

A conformance must be reflexive, symmetric, and transitive. The compiler does not check these rules.

Category: Core.

Profiles: aarch64-apple-darwin, aarch64-unknown-linux-gnu, aarch64-unknown-linux-gnu-no-libc, x86_64-unknown-linux-gnu, x86_64-unknown-linux-gnu-no-libc, wasm32-unknown-unknown, wasm32-wasip1, wasm32-wasip2.

View the source of this page