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

后端 未结 1 579
挽巷
挽巷 2021-01-18 01:22

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

相关标签:
1条回答
  • 2021-01-18 01:58

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

    0 讨论(0)
提交回复
热议问题