๋น„๊ต

์ด๋Ÿฌํ•œ ํŠธ๋ ˆ์ž‡์€ ๊ฐ’ ๊ฐ„์˜ ๋น„๊ต๋ฅผ ์ง€์›ํ•ฉ๋‹ˆ๋‹ค. ๋ชจ๋“  ํŠธ๋ ˆ์ž‡์€ ์ด๋Ÿฌํ•œ ํŠธ๋ ˆ์ž‡์„ ๊ตฌํ˜„ํ•˜๋Š” ํ•„๋“œ๋ฅผ ํฌํ•จํ•˜๋Š” ํƒ€์ž…์— ๋Œ€ํ•ด ์ƒ์†๋  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.

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์„ ๋ฐ˜ํ™˜ํ•ฉ๋‹ˆ๋‹ค.

This slide should take about 10 minutes.

PartialEq๋Š” ์„œ๋กœ ๋‹ค๋ฅธ ํƒ€์ž… ๊ฐ„์— ๊ตฌํ˜„๋  ์ˆ˜ ์žˆ์ง€๋งŒ Eq๋Š” ๊ตฌํ˜„๋  ์ˆ˜ ์—†์Šต๋‹ˆ๋‹ค. ๋ฐ˜์‚ฌ์ ์ด๊ธฐ ๋•Œ๋ฌธ์ž…๋‹ˆ๋‹ค.

struct Key {
    id: u32,
    metadata: Option<String>,
}
impl PartialEq<u32> for Key {
    fn eq(&self, other: &u32) -> bool {
        self.id == *other
    }
}

์‹ค์ œ๋กœ ์ด๋Ÿฌํ•œ ํŠธ๋ ˆ์ž‡์„ ์ƒ์†ํ•˜๋Š” ๊ฒƒ์€ ์ผ๋ฐ˜์ ์ด์ง€๋งŒ ๊ตฌํ˜„ํ•˜๋Š” ๊ฒƒ์€ ๋“œ๋ฌธ ์ผ์ž…๋‹ˆ๋‹ค.