Alternatives to matching floating points

余生长醉 提交于 2019-12-23 08:57:53

问题


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.

My question is then, how do I achieve the equivalent for example with 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), // Causes warning
    _ => println!("x is not 5")
}

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


回答1:


You can use a match guard:

 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.

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).



来源:https://stackoverflow.com/questions/45875142/alternatives-to-matching-floating-points

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!