Why do I get “conflicting implementations of trait” for f32 which does not implement Ord?

前端 未结 1 718
傲寒
傲寒 2020-12-11 19:07

I want a min() method for f32, u32 and i32, so I created a trait Min:

trait Min {
    fn min         


        
相关标签:
1条回答
  • 2020-12-11 19:13

    I believe this is because the compiler can't rule out the possibility that someday, someone will implement Ord for f32. To put it another way: if the compiler didn't act conservatively, it would be a breaking change to ever implement any new trait on existing types. That would severely limit every library's ability to grow without breaking all downstream users.

    There is no direct way around this, as it is an intentional design choice for the language. The closest would be to implement a wrapper type around f32 (i.e. struct OrdF32(f32);) and implement Ord or Min on that, or to use a crate that defines such a wrapper (such as ordered-float).

    0 讨论(0)
提交回复
热议问题