Rust笔记 - PartialOrd trait

570 阅读1分钟

在Rust实现了PartialOrd trait 就可以对类型进行<, >, <=, ==比较了。下面看一下定义:

trait PartialOrd<Rhs = Self>: PartialEq<Rhs> where Rhs: ?Sized {
    fn partial_cmp(&self, other: &Rhs) -> Option<Ordering>;
    fn lt(&self, other: &Rhs) -> bool { ... }
    fn le(&self, other: &Rhs) -> bool { ... }
    fn gt(&self, other: &Rhs) -> bool { ... }
    fn ge(&self, other: &Rhs) -> bool { ... }
}

enum Ordering {
    Less, // self < other
    Equal, // self == other
    Greater, // self > other
}

下面看一下实现的例子:

use std::cmp::{Ordering, PartialEq, PartialOrd};

#[derive(PartialEq)]
struct Any<T> {
    lower: T,
    upper: T,
}

impl<T: PartialOrd> PartialOrd for Any<T> {
    fn partial_cmp(&self, other: &Any<T>) -> Option<Ordering> {
        if self == other {
            Some(Ordering::Equal)
        } else if self.lower >= other.upper {
            Some(Ordering::Greater)
        } else if self.upper <= other.lower {
            Some(Ordering::Less)
        } else {
            None
        }
    }
}

fn main() {
    let a = Any { lower: 1, upper: 2 };
    let b = Any { lower: 2, upper: 3 };
    assert!(a < b);
}