繁体   English   中英

模式匹配浮点数的替代方法是什么?

[英]What are the alternatives to pattern-matching floating point numbers?

Rust 决定在模式中禁止浮点文字:完全允许匹配浮点文字值,不应该是 #41255 它目前是一个警告,但在未来的版本中将是一个硬错误。

如何实现以下代码的无警告等效项?

struct Point {
    x: f64,
    y: f64,
}

let point = Point { x: 5.0, y: 4.0 };

match point {
    Point { x: 5.0, y } => println!("y is {} when x is 5", y),
    _ => println!("x is not 5"),
}
warning: floating-point types cannot be used in patterns
  --> src/main.rs:10:20
   |
10 |         Point { x: 5.0, y } => println!("y is {} when x is 5", y),
   |                    ^^^
   |
   = note: `#[warn(illegal_floating_point_literal_pattern)]` on by default
   = warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release!
   = note: for more information, see issue #41620 <https://github.com/rust-lang/rust/issues/41620>

现在不可能了吗? 我需要改变我对模式的看法吗? 有没有另一种匹配方式?

您可以使用比赛守卫:

match point {
    Point { x, y } if x == 5.0 => println!("y is {} when x is 5", y),
    _ => println!("x is not 5"),
}

这将责任重新推给您,因此它不会产生任何警告。

不过,浮点相等是一个有趣的主题......所以我建议你进一步研究它,因为它可能是错误的来源(我想这就是 Rust 核心团队不想匹配浮点值的原因)。

暂无
暂无

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

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