1

What do I do when I want to call min on integers and floats? For example consider this:

fn foo<T>(v1: T, v2: T)
    where ???
{
   ....
   let new_min = min(v1, v2);
   ....
}

The problem is that min doesn't work for f32. There is another min for floats.

How would I solve this problem?

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
Maik Klein
  • 15,548
  • 27
  • 101
  • 197

1 Answers1

5

Create your own trait that defines the behavior of the various types:

trait Min {
    fn min(self, other: Self) -> Self;
}

impl Min for u8 {
    fn min(self, other: u8) -> u8 { ::std::cmp::min(self, other) }
}

impl Min for f32 {
    fn min(self, other: f32) -> f32 { f32::min(self, other) }
}

fn foo<T>(v1: T, v2: T)
    where T: Min
{
   let new_min = Min::min(v1, v2);
}

As mentioned in other places, floating point comparisons are hard.

There's no one answer to what the result of min(NaN, 0.0) should be, so it's up to you to decide. If you decide that NaN is less than or greater than all other numbers, great! Maybe it's equal to zero! Maybe you should assert that there will never be a NaN...

Community
  • 1
  • 1
Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
  • 1
    Note: it might be worth demonstrating how to implement `Min` automatically for any type implementing `Ord`; it would be simpler than enumerating all integral types. – Matthieu M. Jun 27 '16 at 06:48
  • @MatthieuM. won't we run into [conflicting trait implementations](https://play.rust-lang.org/?gist=4722b115be2efd7b1a28fdc326e5d20d&version=stable&backtrace=0)? At least until specialization... – Shepmaster Jun 27 '16 at 21:46
  • Ah! I misunderstood. When the OP stated "doesn't work" I thought that `min` (and `Ord`) were not implemented for `f32`. Since they are, indeed you would need specialization... – Matthieu M. Jun 28 '16 at 06:55
  • 2
    Since specialization has been implemented — no, specialization won't solve the conflicting trait problem (as `f32: !Ord`), you additionally need [mutually exclusive traits](https://github.com/rust-lang/rfcs/pull/1148). @MatthieuM. – kennytm Apr 13 '17 at 14:32