简体   繁体   English

如何在Rust中自动实现具有浮点数的结构的比较?

[英]How do I automatically implement comparison for structs with floats in Rust?

I'm trying to automatically "derive" comparison functionality for a simple struct like this: 我正在尝试自动为类似这样的简单结构“派生”比较功能:

#[derive(PartialEq, Eq)]
struct Vec3 {
    x: f64,
    y: f64,
    z: f64,
}

However, Rust 1.15.1 complains: 但是,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`

What exactly am I supposed to do to allow the derivation of a default implementation here? 我到底应该怎么做才能在此处派生默认实现?

Rust intentionally does not implement Eq for float types. Rust有意不为浮点类型实现Eq This reddit discussion may shed some more light on why, but the tl;dr is that floating point numbers aren't totally orderable so bizarre edge cases are unavoidable. 关于reddit的讨论可能会更清楚地说明原因,但是tl; dr是浮点数不是完全可排序的,因此不可避免地会出现奇异的边缘情况。

However, if you want to add comparison to your struct, you can derive PartialOrd instead. 但是,如果要向结构添加比较,则可以派生PartialOrd This will give you implementations of the comparative and equality operators: 这将为您提供比较和相等运算符的实现:

#[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
}

The difference between Eq and PartialEq (and hence between Ord and PartialOrd ) is that Eq requires that the == operator form an equivalence relation , whereas PartialOrd only requires that == and != are inverses. EqPartialEq之间(以及因此OrdPartialOrd之间)的PartialOrd在于, Eq要求==运算符形成等价关系 ,而PartialOrd仅要求==!=为逆。 So just as with floats themselves, you should keep that in mind when doing comparisons on instances of your struct. 因此,就像使用浮点数本身一样,在对结构实例进行比较时,应牢记这一点。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM