Code Logo

Ordering with derive(Ord)

Published at25 Jul 2026
Rust Traits & Generics Easy 0 views
Like0

Write a Rust function that defines a Point struct deriving Eq, PartialOrd, and Ord, then checks whether one Point is less than or equal to another using the <= operator. The Ord trait enables total ordering: <, <=, >, >= comparisons based on lexicographic field order.

Rust's comparison traits form a hierarchy: PartialEq (==, !=), Eq (requires PartialEq + reflexivity), PartialOrd (<, <=, >, >= with potential incomparability), and Ord (total ordering with no incomparable values). Deriving Ord requires deriving Eq, PartialOrd, and PartialEq, which the compiler handles automatically.

The derived Ord implementation compares fields in declaration order using lexicographic comparison. For a struct Point { x: i32, y: i32 }, x is compared first. If x values differ, the comparison result is based on x. If x values are equal, y is compared. This matches mathematical tuple ordering and is intuitive for most use cases.

Time complexity is O(n) where n is the number of fields. Space complexity is O(1). The derived implementation is efficient, short-circuiting on the first non-equal field.

Edge cases include comparing identical structs (returns equal/true for <=), negative values (i32 ordering handles negatives correctly), and ensuring all field types implement the required traits for the derives to work.

Example Input & Output

Example 1
Input
(2,1,2,2)
Output
true
Explanation

Same x, compare y

Example 2
Input
(0,0,-1,-1)
Output
false
Explanation

Point(0,0) > Point(-1,-1)

Example 3
Input
(4,4,4,4)
Output
true
Explanation

Equal points are <= each other

Example 4
Input
(5,5,3,3)
Output
false
Explanation

Point(5,5) > Point(3,3)

Example 5
Input
(1,1,2,2)
Output
true
Explanation

Point(1,1) <= Point(2,2)

Algorithm Flow

Recommendation Algorithm Flow for Ordering with derive(Ord)
Recommendation Algorithm Flow for Ordering with derive(Ord)

Solution Approach

#[derive(Eq, PartialEq, PartialOrd, Ord)]
struct Point {
    x: i32,
    y: i32,
}

fn solution(x1: i32, y1: i32, x2: i32, y2: i32) -> bool {
    let p1 = Point { x: x1, y: y1 };
    let p2 = Point { x: x2, y: y2 };
    p1 <= p2
}

Best Answers

rust - Approach 1
#[derive(Eq, PartialEq, PartialOrd, Ord)]
struct Point {
    x: i32,
    y: i32,
}

fn solution(x1: i32, y1: i32, x2: i32, y2: i32) -> bool {
    let p1 = Point { x: x1, y: y1 };
    let p2 = Point { x: x2, y: y2 };
    p1 <= p2
}