Comparisons between signed and unsigned integers?

Rust integer types now have member functions to add signed and unsigned types and check if the result is representable. What about comparisons between signed and unsigned types? These are easy to implement (e.g. x < 0 || (x as u64) < y safely compares signed x with unsigned y), so my question is more about syntax. Has this been proposed somewhere? Is there a reasonable solution that doesn't result in an explosion of methods?

What I really want for this is for mixed-type comparison operators to just work. Because they only return bool, there's no fundamental problems with that like there is for implicit widening.

Unfortunately, it's currently blocked on smarter inference, because it'd be a breaking change right now.

19 Likes

C++ introduced safe comparison functions: https://en.cppreference.com/w/cpp/utility/intcmp

1 Like

That's a very C++ solution -- add a new thing and just tell people not to use the C thing.

For their constraints that makes sense (especially since there's a defined semantic for it right now between types) but hopefully we can do better in Rust.

3 Likes

This raises a question for me that might be more appropriate on URLO. Is it workable to define traits on pairs of types through tuples? E.g. for this application you could imagine a trait Ord2 implemented for (T, T) if T: Ord but also for arbitrary pairs (S, T) if S and T implement Into<i128>. These overlap (which is too bad because we have something like 100 possible comparisons). Is this an anti-pattern?

PartialOrd already has a generic type, so we just need to implement all the u64: PartialOrd<i64> & such. If it weren't for the inference breakage, we could do it tomorrow.

The combinations is a bit of a pain, but they're already done with macros anyway, so it's not a big deal to generate more with macros. (Though it's be nice to have U<N> and just have a generic one. But that's a whole other conversation.)