Code Logo

Compare with derive(PartialEq)

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

Write a Rust function that defines a struct Point with x and y fields, derives the PartialEq trait, and compares two Point instances using the == operator. The PartialEq trait enables equality comparison with == and inequality with !=.

The #[derive(PartialEq)] attribute generates an implementation of std::cmp::PartialEq that compares each field of the struct for equality. Two struct instances are equal if and only if all their corresponding fields are equal. This is the most common way to enable equality comparisons for custom types in Rust.

PartialEq is a core trait in Rust that is required by many standard library features: assert_eq! macro, HashMap keys (when combined with Eq and Hash), sorting with dedup, and the .contains() method on collections. The Eq subtrait (which requires PartialEq) additionally guarantees reflexivity: a == a is always true for all valid values.

Time complexity is O(n) where n is the number of fields, as each field must be compared. Space complexity is O(1). The derived implementation short-circuits on the first non-matching field for efficiency.

Edge cases include floating-point fields (PartialEq works but NaN != NaN due to IEEE 754), string fields compared by value, and ensuring the derive works for structs where all fields implement PartialEq.

Example Input & Output

Example 1
Input
(1,2,3,4)
Output
false
Explanation

Different values are not equal

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

Different y

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

Same values are equal

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

Identical values

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

Negative values equal

Algorithm Flow

Recommendation Algorithm Flow for Compare with derive(PartialEq)
Recommendation Algorithm Flow for Compare with derive(PartialEq)

Solution Approach

#[derive(PartialEq)]
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(PartialEq)]
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
}