Not all values can be matched against a literal pattern

In all of our examples so far, when we matched DemoStruct in a pattern, we matched probability to a variable or to _. That's because probability is a floating point number, which means that two values that are functionally identical might not compare as exactly equal. 

If we try to use a floating-point literal in a pattern (in Rust 1.29), we see a warning like this:

It's just a warning but, as the warning says, it's going to become an error as Rust evolves. We should treat it as an error, regardless, because the pattern will likely not work properly even though it (currently) compiles.

The reason for that, in this case, is that floating point numbers are approximate. They have to fit into a finite number of bits, so they have to be rounded sometimes. That can result in numbers that should be identical in a purely mathematical sense being different because their representations differ in the least significant bits. The least significant bits usually make such a tiny difference that rounding errors don't much matter, but they can throw off an equality comparison.

The upshot is that if we try to use a literal in a pattern that isn't safe to use, Rust will warn us or give us an error. As usual, Rust isn't willing to let a potential problem go unremarked.

If we need to do something like this, we can use match guards to work around the limitation. We're about to learn about them, so keep reading!

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.191.181.252