rustrust-polars

can I use comparison operators overloaded from Rust PartialOrd and PartialEg in Polars in Rust programs?


Below is a Quote from the Operators section in the Polars manual:

In Rust and Python it is possible to use the operators directly (as in + - * / < >) as the language allows operator overloading. For instance, the operator + translates to the .add() method. You can choose the one you prefer.

I have successfully used the overloaded operators +, -, /, * in my Rust with Polars, it works.

However I am unable to use the (PartialOrd and PartialEq) >, <, !=, == overloaded operators in Rust. Is this a Polars documentation error or is my Rust Polars code using the comparison operators >=, <=, etc is incorrect?

let df_numerical = df
    .clone()
    .lazy()
    .select([
        (col("nrs") + lit(5)).alias("nrs + 5"), // OK
        (col("nrs") > lit(5)).alias("nrs > 5"), // Compiler Error is shown below
        (col("nrs") - lit(5)).alias("nrs - 5"), // OK
        (col("nrs") * col("random")).alias("nrs * random"), // OK
        (col("nrs") / col("random")).alias("nrs / random"), // OK
    ])
    .collect()?;
error[E0369]: binary operation `>` cannot be applied to type `polars::prelude::Expr`
   --> src/main.rs:257:25
    |
257 |             (col("nrs") > lit(5)).alias("nrs > 5"),
    |              ---------- ^ ------ polars::prelude::Expr
    |              |
    |              polars::prelude::Expr

The Error indicates that in my Rust program using Polars I have to use the actual function name such as gt rather than using > operator.


Solution

  • The PartialOrd and PartialEq methods all return fixed types bool or Option<Ordering>. They and their operators therefore cannot be used to construct a Expr.

    The Polars documentation is wrong and should exclude <, >, ==, etc. from the possible operators in Rust.

    I've posted an issue about that