gpt4 book ai didi

rust - 模式匹配 float 的替代方案是什么?

转载 作者:行者123 更新时间:2023-11-29 07:46:03 25 4
gpt4 key购买 nike

Rust 已决定在模式中禁止浮点字面值:Matching on floating-point literal values is totally allowed and shouldn't be #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"),
}

这会将责任推回给您,因此不会产生任何类型的警告。

Floating point equality is an interesting subject though ...所以我建议您进一步研究它,因为它可能是错误的来源(我想这是 Rust 核心团队不想匹配浮点值的原因)。

关于rust - 模式匹配 float 的替代方案是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45875142/

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