Comparison Operators

Comparison operators compare two values and produce a bool result.

Equality Operators

Equality operators work on integers, booleans, strings, the unit type, and struct types.

OperatorNameDescription
==EqualTrue if operands are equal
!=Not equalTrue if operands are not equal

Two strings are equal if they have the same length and identical byte content.

Two unit values are always equal.

Two struct values are equal if and only if they have the same struct type and all corresponding fields are equal.

fn main() -> i32 {
    let a = 1 == 1;    // true
    let b = 1 != 2;    // true
    let c = true == false;  // false (bool equality)
    let d = "hello" == "hello";  // true (string equality)
    let e = () == ();  // true (unit equality)
    if a && b && !c && d && e { 1 } else { 0 }
}
struct Point { x: i32, y: i32 }

fn main() -> i32 {
    let p1 = Point { x: 1, y: 2 };
    let p2 = Point { x: 1, y: 2 };
    let p3 = Point { x: 1, y: 3 };
    if p1 == p2 && p1 != p3 { 1 } else { 0 }
}

Ordering Operators

Ordering operators work only on integers.

OperatorNameDescription
<Less thanTrue if left < right
>Greater thanTrue if left > right
<=Less or equalTrue if left <= right
>=Greater or equalTrue if left >= right

Ordering operators on boolean, string, unit, or struct values are a compile-time error. Implementations MUST reject such programs.

fn main() -> i32 {
    let a = 1 < 2;     // true
    let b = 5 >= 5;    // true
    if a && b { 1 } else { 0 }
}

Precedence

Comparison operators have lower precedence than arithmetic operators.

fn main() -> i32 {
    if 1 + 2 == 3 { 1 } else { 0 }  // 1 (comparison after arithmetic)
}

Type Checking

Both operands of a comparison MUST have the same type.

When one operand has a known type, the other is inferred to have the same type.

Associativity

Comparison operators cannot be chained. Expressions like a < b < c or a == b == c are compile-time errors.

To compare multiple values, use logical operators:

fn main() -> i32 {
    let a = 1;
    let b = 2;
    let c = 3;
    if a < b && b < c { 1 } else { 0 }  // correct way to chain comparisons
}