如何按 Chronos DateTime 字段对结构向量进行排序?

How to Sort Vector of Structs by Chronos DateTime Field?

我有这个结构

pub struct Items {
    pub symbol: String,
    pub price: f64,
    pub date: DateTime<Utc>,
}

我有这些结构的向量。我想按日期对它们进行排序。我该怎么做呢?我尝试推导 PartialEq、Ord、Eq 等...但是 Rust 抱怨浮点字段。

最简单的方法是使用为 Vec 实现的排序函数之一,例如 sort_bysort_by_keysort_by_key_cached

// Using sort_by
foo_items.sort_by(|a, b| a.date.cmp(&b.date));

// Using sort_by_key
foo_items.sort_by_key(|x| x.date);

// Using sort_by_key_cached (Faster if key is very large)
foo_items.sort_by_cached_key(|x| x.date);

并且不要忘记,您始终可以选择手动实现通常派生的特征。

use std::cmp::Ordering;

impl PartialEq for Items {
    fn eq(&self, other: &Self) -> bool {
        // idk what symbol is, but use it anyway
        self.symbol == other.symbol && self.date == other.date
    }
}

impl Eq for Items {}

impl PartialOrd for Items {
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        self.date.partial_cmp(&other.date)
    }
}

impl Ord for Items {
    fn cmp(&self, other: &Self) -> Ordering {
        self.date.cmp(&other.date)
    }
}
#[derive(Debug)]
pub struct S {
    pub s: f64,
    
}


fn main() {
    let mut v = vec![S{s:0.3}, S{s:1.3}, S{s:7.3}]; 

    v.sort_by(|a, b| a.s.partial_cmp(&b.s).unwrap());

    println!("{:#?}",v);
}