Deriving PartialOrd Trait

Hello, I'm currently getting familiar with traits, and want to make sure my understanding of deriving PartialOrd is correct.

Let's say I make a type Date. It will be printed as follows: [month]/[day]/[year]

I might be tempted to create the struct using that order:

struct Date {
    month: u8,
    day: u8,
    year: u8,
}

But, according to PartialOrd:

"When derived on structs, it will produce a lexicographic ordering based on the top-to-bottom declaration order of the struct’s members."

Based on this, I see two approaches I can take:

  1. Manually implement PartialOrd to specify the order; or
  2. Arrange the members in the desired order and derive; i.e.
#[derive(PartialOrd)]
struct Date {
    year: u8,
    month: u8,
    day: u8,
}

Is my understanding of this correct?

Yes.

Incidentally you can use Tools > Expand macros in the playground to check your understanding.

4 Likes

That is fantastic, thank you!

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.