模式匹配浮点数有哪些替代方法? [英] What are the alternatives to pattern-matching floating point numbers?

查看:76
本文介绍了模式匹配浮点数有哪些替代方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Rust已决定禁止使用模式中的浮点文字:匹配浮点文字值完全允许,不应为#41255 .当前是警告,但在将来的版本中将是硬错误.

Rust has decided to disallow float literals in patterns: Matching on floating-point literal values is totally allowed and shouldn't be #41255. It is currently a warning but will be a hard error in a future release.

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

How do I achieve a warning-free equivalent of the following code?

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>

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

Is it now impossible? Do I need to change how I think about patterns? Is there another way of matching it?

推荐答案

您可以使用比赛防护:

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

这会将责任重新带给您,因此不会产生任何警告.

This puts the responsibility back on to you, so it doesn't produce any sort of warning.

浮点数相等是一个有趣的话题 ...所以我会建议您进一步研究它,因为它可能是错误的来源(我想这是Rust核心团队不希望与浮点值匹配的原因).

Floating point equality is an interesting subject though... so I would advise that you look further into it since it may be a source of bugs (which I imagine is the reason the Rust core team don't want to match against floating point values).

这篇关于模式匹配浮点数有哪些替代方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆