Compare with derive(PartialEq)
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
Different values are not equal
Different y
Same values are equal
Identical values
Negative values equal
Algorithm Flow

Solution Approach
Best Answers
#[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
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
