gpt4 book ai didi

comparison - 如何在 Rust 中自动实现结构与 float 的比较?

转载 作者:行者123 更新时间:2023-11-29 08:33:17 26 4
gpt4 key购买 nike

我正在尝试为这样的简单结构自动“导出”比较功能:

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

然而,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`

我究竟应该做什么才能允许在这里派生默认实现?

最佳答案

Rust 有意不为浮点类型实现 Eq。这reddit discussion可能会更清楚地说明原因,但 tl;dr 是 float 不是完全可排序的,所以奇怪的边缘情况是不可避免的。

但是,如果您想将比较添加到您的结构中,您可以改为派生 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
}

EqPartialEq 之间的区别(以及 OrdPartialOrd 之间的区别)是 Eq 要求 == 运算符形成一个 equivalence relation ,而 PartialOrd 只要求 ==!= 是逆的。因此,就像 float 本身一样,在对结构的实例进行比较时应牢记这一点。

关于comparison - 如何在 Rust 中自动实现结构与 float 的比较?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42333349/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com