Implementing `Hash`, `Ord` etc for an enum using floats


#1

Imagine a scenario like this:

enum MyEnum {
    Float(f64),
    Int(i64),
}

I can’t derive Hash or Ord for MyEnum, so I can’t simply use vec.sort() if vec has type Vec<MyEnum>, and I also can’t just use MyEnum values as entries in a HashSet for example.

The obvious thing to do would seem to manually implement the traits for MyEnum, but if it were that easy to work out the specifics I think that it would already have been done in std.

Let’s assume I need to be able to use MyEnum values in a HashSet anyway. Keeping in mind that one enum variant contains an f64, how would I go about implementing the Hash, Ord etc traits without violating the contracts provided by those traits?


#2

The ordered-float crate has already done the hard work for you by providing a NotNan wrapper type. Use this in your struct and you’ll be able to derive Hash and Ord.


#3

Lol this is as predictable as it is awesome: someone’s already done the work.
Thank you for pointing me to this, it’ll save me a bunch of work :slight_smile: