How to sort Vec<enum>

Hi, I tried to sort Vec<enum> because enum is 0...n numbers. But compile failed, any suggestion? Thanks!

use crate::Update::{Two, Zero, One};

enum Update {
fn main() {
    let mut v:Vec<Update> = vec![Two, Zero, One];
    // I expect [Zero, One, Two]
    println!("{:?}",v );
   --> src\
3   | #[derive(Debug,Ord,PartialOrd)]
    |                    ^^^^^^^^^^ no implementation for `Update == Update`
   ::: C:\Users\zhu_s\.rustup\toolchains\stable-x86_64-pc-windows-msvc\lib/rustlib/src/rust\library\core\src\
921 | pub trait PartialOrd<Rhs: ?Sized = Self>: PartialEq<Rhs> {
    |                                           -------------- required by this bound in `PartialOrd`
    = help: the trait `PartialEq` is not implemented for `Update`
    = note: this error originates in a derive macro (in Nightly builds, run with -Z macro-backtrace for more info)
1 Like


It's exactly like the error message tells you. Update does not implement PartialEq and therefore sort() can not be used on a Vec<Update>


  1. sort() is a method from the primitive slice. As Vec<T> implements Deref<Target = [T]> you can use methods from slices directly on a Vec.
  2. The signature of sort() is
    fn sort(&mut self) where T: Ord
    Which means Update is required to implement Ord .
  3. Ord in turn requires that types implementing Ord also implement Eq and PartialOrd.
  4. Eq in turn requires types implementing Eq to implement PartielEq, therefore, the compiler complains about Update not implementing PartialEq.


The simple solution is to implement Eq and PartialEq via derive macros. Here the solution in the playground.

If you wonder why there are so many traits for ordering and equality I recommend reading the excellent documentation pages.


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.