Why do I get "conflicting trait implementations" for f32 that does not implement Ord?

I need the min() method for f32 , u32 and i32 , so I created the Min sign:

 trait Min { fn min(v1: Self, v2: Self) -> Self; } impl<T> Min for T where T: Ord { fn min(v1: Self, v2: Self) -> Self { ::std::cmp::min(v1, v2) } } impl Min for f32 { fn min(v1: Self, v2: Self) -> Self { v1.min(v2) } } 

I get an error message:

 error[E0119]: conflicting implementations of trait `Min` for type `f32`: --> src/main.rs:11:1 | 5 | / impl<T> Min for T where T: Ord { 6 | | fn min(v1: Self, v2: Self) -> Self { 7 | | ::std::cmp::min(v1, v2) 8 | | } 9 | | } | |_- first implementation here 10 | 11 | / impl Min for f32 { 12 | | fn min(v1: Self, v2: Self) -> Self { 13 | | v1.min(v2) 14 | | } 15 | | } | |_^ conflicting implementation for `f32` 

According to the documentation of the Rust standard library, f32 does not implement Ord . Why are there conflicting implementations?

+3
source share
1 answer

I believe this is due to the fact that the compiler cannot rule out the possibility that someday someone will implement Ord for f32 . In other words: if the compiler hadn’t acted conservatively, it would be a terrific change to ever implement some new feature of existing types. This would seriously limit the ability of each library to grow without disrupting all subsequent users.

There is no direct path, as this is a deliberate choice of design for the language. The closest would be to implement a shell type around f32 (i.e., struct OrdF32(f32); ) and implement Ord or Min on it or use a box that defines such a shell (e.g. ordered-float ).

+4
source

Source: https://habr.com/ru/post/1269865/


All Articles