pub trait PartialEq {
/// Evaluates if two values of the same type are equal.
///
/// # Arguments
///
/// * `other`: [Self] - The value of the same type.
///
/// # Returns
///
/// * [bool] - `true` if the values are equal, otherwise `false`.
///
/// # Examples
///
/// ```sway
/// struct MyStruct {
/// val: u64,
/// }
///
/// impl PartialEq for MyStruct {
/// fn eq(self, other: Self) -> bool {
/// self.val == other.val
/// }
/// }
///
/// fn foo() {
/// let struct1 = MyStruct { val: 2 };
/// let struct2 = MyStruct { val: 2 };
/// let result = struct1 == struct2;
/// assert(result);
/// }
/// ```
fn eq(self, other: Self) -> bool;
} {
/// Evaluates if two values of the same type are not equal.
///
/// # Additional Information
///
/// This function is inherited when `eq()` is implemented.
///
/// # Arguments
///
/// * `other`: [Self] - The value of the same type.
///
/// # Returns
///
/// * [bool] - `true` if the two values are not equal, otherwise `false`.
///
/// # Examples
///
/// ```sway
/// struct MyStruct {
/// val: u64,
/// }
///
/// impl PartialEq for MyStruct {
/// fn eq(self, other: Self) -> bool {
/// self.val == other.val
/// }
/// }
///
/// fn foo() {
/// let struct1 = MyStruct { val: 10 };
/// let struct2 = MyStruct { val: 2 };
/// let result = struct1 != struct2;
/// assert(result);
/// }
/// ```
fn neq(self, other: Self) -> bool {
(self.eq(other)).not()
}
}
Expand description
Trait for comparing type instances using the equality operator.
Implementing this trait provides ==
and !=
operators on a type.
This trait allows comparisons for types that do not have a full equivalence relation.
In other words, it is not required that each instance of the type must be
equal to itself. While most of the types used in blockchain development do have this
property, called reflexivity, we can encounter types that are not reflexive.
A typical example of a type supporting partial equivalence, but not equivalence,
is a floating point number, where NaN
is different from any other number,
including itself: NaN != NaN
.
Required Methods
fn eq(self, other: Self) -> bool
fn eq(self, other: Self) -> bool
Evaluates if two values of the same type are equal.
Arguments
other
: [Self] - The value of the same type.
Returns
- [bool] -
true
if the values are equal, otherwisefalse
.
Examples
struct MyStruct {
val: u64,
}
impl PartialEq for MyStruct {
fn eq(self, other: Self) -> bool {
self.val == other.val
}
}
fn foo() {
let struct1 = MyStruct { val: 2 };
let struct2 = MyStruct { val: 2 };
let result = struct1 == struct2;
assert(result);
}