问题描述
我想要 f32
、u32
和 i32
的 min()
方法,所以我创建了一个特征最小
:
I want a min()
method for f32
, u32
and i32
, so I created a trait Min
:
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)
}
}
我收到一个错误:
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`
根据 Rust 标准库文档,f32
没有实现 Ord
.为什么会出现相互冲突的实现?
According to the Rust standard library documentation, f32
does not implement Ord
. Why there are conflicting implementations?
推荐答案
我相信这是因为编译器不能排除有朝一日有人将实现Ord的可能性
f32
的代码>.换句话说:如果编译器没有保守地采取行动,那么在现有类型上实现任何新特性将是一个突破性的变化.这将严重限制每个图书馆在不影响所有下游用户的情况下发展壮大的能力.
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.
没有直接的方法可以解决这个问题,因为它是语言的有意设计选择.最接近的是实现一个包装器类型 around f32
(ie struct OrdF32(f32);
) 并实现Ord
或 Min
在 that 上,或者使用定义此类包装器的 crate(例如 ordered-float
).
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
).
这篇关于为什么我会得到“特性的冲突实现"?对于未实现 Ord 的 f32?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!