编写一系列浮点范围比较的最佳方法是什么?要使用下面GitHub评论中的示例,
let color = match foo {
0.0...0.1 => Color::Red,
0.1...0.4 => Color::Yellow,
0.4...0.8 => Color::Blue,
_ => Color::Grey,
};
Run Code Online (Sandbox Code Playgroud)
天真的解决方案将是一个痛苦的if-else链:
let color = {
if 0.0 <= foo && foo < 0.1 {
Color::Red
}
else if 0.1 <= foo && foo < 0.4 {
Color::Yellow
}
else if 0.4 <= foo && foo < 0.8 {
Color:: Blue
}
else {
Color::Grey
}
}
Run Code Online (Sandbox Code Playgroud)
这真的是最好的选择吗?必须有一个更好的方式来写这个,对吧?
与匹配浮点的替代相关,但这是用于范围比较.
本来中提到的跟踪问题的illegal_floating_point_literal_pattern,有事我运行到不断.
tre*_*tcl 11
从 Rust 1.35 开始,Boiethios 实现的InRange功能已经在方法中提供:containsRange<f32>
impl From<f32> for Color {
fn from(f: f32) -> Color {
match f {
x if (0.0..0.1).contains(&x) => Color::Red,
x if (0.1..0.4).contains(&x) => Color::Yellow,
x if (0.4..0.8).contains(&x) => Color::Blue,
_ => Color::Grey,
}
}
}
Run Code Online (Sandbox Code Playgroud)
但是,我倾向于只对每个数字进行一次比较来写这个,这样可以减少输入错误的机会:
impl From<f32> for Color {
fn from(f: f32) -> Color {
match f {
x if x < 0.0 => Color::Grey;
x if x < 0.1 => Color::Red,
x if x < 0.4 => Color::Yellow,
x if x < 0.8 => Color::Blue,
_ => Color::Grey,
}
}
}
Run Code Online (Sandbox Code Playgroud)
这种风格也使得返回Color::Grey:x < 0.0和 的两个不相交范围变得更加明显x >= 0.8。
我个人会这样做:
#[derive(Debug, PartialEq)]
enum Color {
Red,
Yellow,
Blue,
Grey,
}
trait InRange {
fn in_range(self, begin: Self, end: Self) -> bool;
}
impl InRange for f32 {
fn in_range(self, begin: f32, end: f32) -> bool {
self >= begin && self < end
}
}
impl From<f32> for Color {
fn from(f: f32) -> Color {
match f {
x if x.in_range(0.0, 0.1) => Color::Red,
x if x.in_range(0.1, 0.4) => Color::Yellow,
x if x.in_range(0.4, 0.8) => Color::Blue,
_ => Color::Grey,
}
}
}
fn main() {
assert_eq!(Color::from(0.2), Color::Yellow);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
531 次 |
| 最近记录: |