Comparison Traits – Understanding Equality and Ordering in Rust

itsfoxstudio.substack.com

57 points by rpunkfu 9 days ago


thomasmg - 3 days ago

I find floating point NaN != NaN quite annoying. But this is not related to Rust: this affects all programming languages that support floating point. All libraries that want to support ordering for floating point need to handle this special case, that is, all sort algorithms, hash table implementation, etc. Maybe it would cause less issues if NaN doesn't exist, or if NaN == NaN. At least, it would be much easier to understand and more consistent with other types.

tialaramex - 3 days ago

One thing that isn't discussed here but seems worth knowing for a HN audience is that these are what Rust calls "safe" traits. This has several related consequences

1. You don't need to utter the keyword "unsafe" to implement these traits for your type. If you're not allowed by policy to write unsafe Rust (or if you just don't want to risk making any mistakes), you can implement these traits anyway. If you do that you should do so correctly as with writing any software...

2. But, because they're safe traits, nobody else's Rust software is allowed to rely on your correctness. If you disobeyed a rule, such as you decide all values of your type are always greater than themselves (whether carelessly or because you're a vandal) other Rust software mustn't become unsafe as a result.

3. This has real world implications, for example if your type Goose has an Ord implementation which is defective, whether on purpose or by mistake, sorting a Vec<Goose> in Rust won't have Undefined Behaviour like in C++, it might panic (in debug) and it can't necessarily sort your type if your Ord implementation is nonsensical, but the "sorted" Vec<Goose> is the same geese as your original, just potentially in a sorted state to the extent that meant anything. It's not fewer geese, or more geese, or just different geese altogether - and it certainly isn't say, an RCE now like it might be in C++

mattrighetti - 3 days ago

I was blown away when I discovered that Rust automatically generates enum ordering. I remember I was coding an AoC solution [0] and the tests that I had set up were passing without me actually doing any work, good times! :)

[0]: https://mattrighetti.com/2023/12/07/aoc-day-7

Apaec - 2 days ago

Is this a political blog post? I see Rust and Equality in the title..