本文介绍了如何在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,
}

但是,Rust 1.15.1抱怨:

However, Rust 1.15.1 complains:

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有意不实现等式用于浮点类型。此可能会进一步说明原因,但tl

Rust intentionally does not implement Eq for float types. 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.

但是,如果要对结构添加比较,则可以导出 PartialOrd 。这将为您提供比较和相等运算符的实现:

However, if you want to add comparison to your struct, you can derive PartialOrd instead. 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
}

Eq PartialEq (因此在 Ord PartialOrd )是 Eq 要求 == 运算符形成,而 PartialOrd 仅要求 == != 是逆的。因此,就像使用浮点数本身一样,在对结构实例进行比较时也应牢记这一点。

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. So just as with floats themselves, you should keep that in mind when doing comparisons on instances of your struct.

这篇关于如何在Rust中自动实现具有浮点数的结构的比较?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

11-02 20:32