Horowitzathome
Horowitzathome

Reputation: 439

Use a reference to a compare operator or function to compare some values

Is there a way to have a reference to a compare operator or function in Rust to compare some values? So what I have in my mind would be ...

enum SomeEnum {
    A,
    B,
}

let some_enum = SomeEnum::A;
let a = 1;
let b = 2;

// What would be nice ...
let op = match some_enum {
    SomeEnum::A => {
        ge_operator // return greater_equal operator - how could this work?
    }
    SomeEnum::B => {
       ls_operator // return less operator - how could this work?
    }
};
    
let test = if a op b {
    'X'
} else {
    'Y'
};

Upvotes: 2

Views: 558

Answers (1)

Netwave
Netwave

Reputation: 42698

You can return functions as needed in the match scope:

// What would be nice ...
let op = match some_enum {
    SomeEnum::A => {
        <u32 as PartialOrd<u32>>::ge // return greater_equal operator - how could this work?
    }
    SomeEnum::B => {
        <u32 as PartialOrd<u32>>::lt // return less operator - how could this work?
    }
};

Playground

As @eggyal points out, rust can even infer the type:

let op = match some_enum {
    SomeEnum::A => PartialOrd::ge,
    SomeEnum::B => PartialOrd::lt,
};

Upvotes: 3

Related Questions