λΉκ΅
μ΄λ¬ν νΈλ μμ κ° κ°μ λΉκ΅λ₯Ό μ§μν©λλ€. λͺ¨λ νΈλ μμ μ΄λ¬ν νΈλ μμ ꡬννλ νλλ₯Ό ν¬ν¨νλ νμ μ λν΄ μμλ μ μμ΅λλ€.
PartialEq and Eq
PartialEqλ νμ λ©μλμΈ eq λ° μ 곡λ ne λ©μλλ₯Ό μ¬μ©νλ λΆλΆ λ±κ° κ΄κ³μ
λλ€. == λ° != μ°μ°μλ μ΄λ¬ν λ©μλλ₯Ό νΈμΆν©λλ€.
struct Key {
id: u32,
metadata: Option<String>,
}
impl PartialEq for Key {
fn eq(&self, other: &Self) -> bool {
self.id == other.id
}
}
Eq is a full equivalence relation (reflexive, symmetric, and transitive) and implies PartialEq. Functions that require full equivalence will use Eq as a trait bound.
PartialOrd λ° Ord
PartialOrdλ partial_cmp λ©μλλ₯Ό μ¬μ©νμ¬ λΆλΆ μμλ₯Ό μ μν©λλ€. <, <=, >=, > μ°μ°μλ₯Ό ꡬννλ λ° μ¬μ©λ©λλ€.
use std::cmp::Ordering;
#[derive(Eq, PartialEq)]
struct Citation {
author: String,
year: u32,
}
impl PartialOrd for Citation {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
match self.author.partial_cmp(&other.author) {
Some(Ordering::Equal) => self.year.partial_cmp(&other.year),
author_ord => author_ord,
}
}
}
Ordλ μ 체 μμ μ§μ μ΄λ©° cmpλ Orderingμ λ°νν©λλ€.
PartialEqλ μλ‘ λ€λ₯Έ νμ
κ°μ ꡬνλ μ μμ§λ§ Eqλ ꡬνλ μ μμ΅λλ€. λ°μ¬μ μ΄κΈ° λλ¬Έμ
λλ€.
struct Key {
id: u32,
metadata: Option<String>,
}
impl PartialEq<u32> for Key {
fn eq(&self, other: &u32) -> bool {
self.id == *other
}
}
μ€μ λ‘ μ΄λ¬ν νΈλ μμ μμνλ κ²μ μΌλ°μ μ΄μ§λ§ ꡬννλ κ²μ λλ¬Έ μΌμ λλ€.