notriddle / rust-float-ord

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Confusing error: unsatisfied trait bounds `FloatOrd<&f32>: Iterator`

EdmundsEcho opened this issue · comments

I have no idea why I'm getting this missing implementation error.

impl Ord for AnyNumber {
    fn cmp(&self, other: &Self) -> Ordering {
        match (self, other) {
            (AnyNumber::UInt8(a), AnyNumber::UInt8(b)) => a.cmp(b),
            (AnyNumber::UInt16(a), AnyNumber::UInt16(b)) => a.cmp(b),
            ...
            (AnyNumber::Float32(a), AnyNumber::Float32(b)) => FloatOrd(a).cmp(FloatOrd(b)),
            (AnyNumber::Float64(a), AnyNumber::Float64(b)) => FloatOrd(a).cmp(FloatOrd(b)),
            _ => panic!("Tried to combine different type values"),
        }
    }
}

The error

error[E0599]: `FloatOrd<&f32>` is not an iterator
  --> /Users/edmund/Programming-Local/tnc-analysis/lib/src/lib.rs:65:75
   |
65 |             (AnyNumber::Float32(a), AnyNumber::Float32(b)) => FloatOrd(a).cmp(FloatOrd(b)),
   |                                                                           ^^^ `FloatOrd<&f32>` is not an iterator
   |
  ::: /Users/edmund/.cargo/registry/src/github.com-1ecc6299db9ec823/float-ord-0.3.2/src/lib.rs:15:1
   |
15 | pub struct FloatOrd<T>(pub T);
   | ---------------------- doesn't satisfy `FloatOrd<&f32>: Iterator`
   |
   = note: the following trait bounds were not satisfied:
           `FloatOrd<&f32>: Iterator`
           which is required by `&mut FloatOrd<&f32>: Iterator`

Any ideas?

Try FloatOrd(*a).cmp(FloatOrd(*b))

I had tried that. However, given that you also suggested it, I tried it "a bit harder" :)). The following shenanigans worked:

// snippet from a fn that returns `Ordering`
(AnyNumber::Float32(a), AnyNumber::Float32(b)) => *&FloatOrd(*a).cmp(&FloatOrd(*b)),

Funny looking... it's not even a re-borrow per se.

Is there a trait that might help make this more user-friendly? I wonder what makes my a different? Finally, I get how Iterator can be used to unwrap a single value (e.g., Option), but can't see it here.

The trouble here is that cmp is a function that iterators have, but, in this context, you don't want Iterator::cmp, you want PartialOrd::cmp.

Thank you for clarifying and your prompt replies. I was unable to compile the code until I saw your response this morning (EST).

I did not know about Iterator::cmp. I'll try to rework the code using the qualified call to PartialOrd::cmp.