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.
a < b < c vs. Rust:
In Rust, you can achieve a similar result to Python’s
a < b < c using the
contains() method with a range:
let c_in_range = (a..b).contains(&c);
a < b <= c vs. Rust:
Similarly, for comparisons like
a < b <= c, you can use the inclusive range operator in Rust and the
let c_in_range = (a..=b).contains(&c);
This approach maintains readability and provides a Rust equivalent to Python’s chaining comparisons.
In the future, when
is_sorted() method for iterators makes it to mainline Rust, it will bring even more possibilities for chained comparisons:
a <= b <= c vs. Rust:
[a, b, c].is_sorted()
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.