我正在尝试为这样的简单结构自动"派生"比较功能:
#[derive(PartialEq, Eq)]
struct Vec3 {
x: f64,
y: f64,
z: f64,
}
Run Code Online (Sandbox Code Playgroud)
但是,Rust 1.15.1抱怨:
error[E0277]: the trait bound `f64: std::cmp::Eq` is not satisfied
--> src/main.rs:3:5
|
3 | x: f64,
| ^^^^^^ the trait `std::cmp::Eq` is not implemented for `f64`
|
= note: required by `std::cmp::AssertParamIsEq`
Run Code Online (Sandbox Code Playgroud)
我应该做些什么来允许在此推导出默认实现?
Dan*_*mon 13
Rust故意不Eq为float类型实现.这个reddit讨论可能会更多地阐明原因,但是tl; dr是浮点数不是完全可订购的,所以奇怪的边缘情况是不可避免的.
但是,如果要向结构添加比较,则可以派生PartialOrd.这将为您提供比较和相等运算符的实现:
#[derive(PartialEq, PartialOrd)]
struct Vec3 {
x: f64,
y: f64,
z: f64,
}
fn main() {
let a = Vec3 { x: 1.0, y: 1.1, z: 1.0 };
let b = Vec3 { x: 2.0, y: 2.0, z: 2.0 };
println!("{}", a < b); //true
println!("{}", a <= b); //true
println!("{}", a == b); //false
}
Run Code Online (Sandbox Code Playgroud)
Eq和之间PartialEq(以及之间Ord和之间PartialOrd)之间的区别在于,Eq要求==运算符形成等价关系,而PartialOrd只需要==和!=反转.就像浮动本身一样,在对结构实例进行比较时应该记住这一点.
| 归档时间: |
|
| 查看次数: |
3097 次 |
| 最近记录: |