Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 967
Tom Avatar asked Aug 25 '17 05:08

Tom


1 Answers

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

like image 113
Simon Whitehead Avatar answered Jan 17 '23 22:01

Simon Whitehead