Chaining Comparisons in Python and Rust
I love chaining comparisons in Python. Not only are expressions like a < b < c terser, but I also find them more readable than the alternative (a < b and b < c). So when I started coding in Rust, I wanted something similar.
Limitation in Rust
Unfortunately, Rust does not support chaining operators. The arguments are revolving around cases where the interpretation would not be obvious (a != b != c), or situations where they they could potentially decrease readability when used incorrectly. Those are fair points. But luckily, there are alternative approaches to achieve the same goals in Rust.
Alternative approaches
Python: a <= b <= c vs. Rust: (a..=c).contains(&b)
For comparisons like a <= b <= c, you can use the inclusive range operator in Rust and the contains() method:
let b_in_range = (a..=c).contains(&b);
This approach maintains readability and provides a Rust equivalent to Python’s chaining comparisons.
Python: a < b < c vs. Rust: ((a + 1)..c).contains(&b)
Non-inclusive comparisons are harder to achieve in Rust, because the contains() method’s lower bound is inclusive. You could explicitly add 1 to it, to achieve comparison similar to Python’s a < b < c:
let b_in_range = ((a + 1)..c).contains(&b);
But be cautious with this approach, as it may not work correctly for all types (e.g., floating-point numbers), and is prone to other errors. You should also consider whether this approach improves readability in your specific context. (I would argue it does not in most cases.)
Looking forward
In the future, when is_sorted() method for iterators makes it to mainline Rust, it will bring even more possibilities for chained comparisons:
Python: a <= b <= c vs. Rust: [a, b, c].is_sorted()
Conclusion
While Rust may lack direct support for chaining comparisons, it offers alternative approaches to maintain code readability and expressiveness. These make coding in Rust just as enjoyable and concise as in Python, once you get the hang of them.
Thanks to Vivian McKnight for pointing out errors in the contains() examples.