Home > Net >  How to Sort Vector of Structs by Chronos DateTime Field?
How to Sort Vector of Structs by Chronos DateTime Field?

Time:04-20

I have this struct

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

I have a vector of these structs. I would like to sort them by date. How would I go about doing that? I tried deriving PartialEq, Ord, Eq, etc... but Rust complains about the float fields.

CodePudding user response:

The easiest way is to use one of the provides sort functions implemented for Vec like sort_by, sort_by_key, or sort_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);

And don't forget you always have the option to manually implement traits that are normally derived.

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)
    }
}

CodePudding user response:

#[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);
}
  • Related